Exemple #1
0
 void SelectFont()
 {
     _c.SetFont(CGFont.CreateWithFontName(_lastFont.FontFamily));
     _c.SetFontSize(_lastFont.FontSize);
     _c.SetFont(_lastFont.ToUIFont());
     _c.TextMatrix = _textMatrix;
 }
Exemple #2
0
        private static void InitTypefaceWeightRamp()
        {
            lock (InitSyncObject)
            {
                if (null == FontRamp)
                {
                    CGFont[] fontRamp = new CGFont[5];

                    // Weight 100

                    fontRamp[0] = CGFont.CreateWithFontName("AvenirNext-UltraLight");

                    // Weight 300

                    fontRamp[1] = CGFont.CreateWithFontName("AvenirNext-Regular");

                    // Weight 400

                    fontRamp[2] = CGFont.CreateWithFontName("AvenirNext-Medium");

                    // Weight 500

                    fontRamp[3] = CGFont.CreateWithFontName("AvenirNext-DemiBold");

                    // Weight 700

                    fontRamp[4] = CGFont.CreateWithFontName("AvenirNext-Bold");

                    FontRamp = fontRamp;
                }
            }
        }
Exemple #3
0
 public static CTFont ToCTFont(this Font font)
 {
     using (var cgFont = CGFont.CreateWithFontName(font.Name))
     {
         return(new CTFont(cgFont, font.Size, CGAffineTransform.MakeIdentity()));
     }
 }
Exemple #4
0
 public void GetGlyphWithGlyphName()
 {
     using (var f = CGFont.CreateWithFontName("Courier New")) {
         Assert.That(f.Handle, Is.Not.EqualTo(IntPtr.Zero), "CreateWithFontName");
         // note: the API is marked to accept a null CFStringRef but it currently (iOS9 beta 4) crash when provided one
         Assert.Throws <ArgumentNullException> (() => f.GetGlyphWithGlyphName(null), "GetGlyphWithGlyphName");
     }
 }
Exemple #5
0
 public void GetGlyphsForCharacters_35048()
 {
     using (var font = CGFont.CreateWithFontName("AppleColorEmoji"))
         using (var ctfont = font.ToCTFont((nfloat)10.0)) {
             ushort[] gid = new ushort [2];
             Assert.True(ctfont.GetGlyphsForCharacters("\ud83d\ude00".ToCharArray(), gid), "GetGlyphsForCharacters");
             Assert.That(gid [0], Is.Not.EqualTo(0), "0");
             Assert.That(gid [1], Is.EqualTo(0), "1");
         }
 }
Exemple #6
0
        public void CTFontCopyNameForGlyph()
        {
            TestRuntime.AssertXcodeVersion(12, 0);

            using (var ctfont = new CTFont("HoeflerText-Regular", 10, CTFontOptions.Default))
                Assert.That(ctfont.GetGlyphName((ushort)65), Is.EqualTo("asciicircum"), "1");

            using (var font = CGFont.CreateWithFontName("AppleColorEmoji"))
                using (var ctfont = font.ToCTFont((nfloat)10.0))
                    Assert.Null(ctfont.GetGlyphName('\ud83d'), "2");
        }
Exemple #7
0
        public void GetBoundingRect_WithEmptyGlyphs()
        {
            CGFont cgFont = CGFont.CreateWithFontName("Arial");

            ushort [] glyphs = new ushort [] {};

            CTFont ctFont = new CTFont(cgFont, 14, new CTFontDescriptor("Arial", 14));
            NSFont nsFont = NSFont.FromCTFont(ctFont);

            Assert.Throws <ArgumentException> (() => nsFont.GetBoundingRects(glyphs));
            Assert.Throws <ArgumentException> (() => nsFont.GetAdvancements(glyphs));
        }
Exemple #8
0
        public CGFont GetCustomFont(string name)
        {
            if (name == null)
            {
                return(CGFont.CreateWithFontName(_systemFontName));
            }

            if (_customFonts.TryGetValue(name, out var font))
            {
                return(font);
            }

            return(CGFont.CreateWithFontName(_systemFontName));
        }
        private static Tuple <NSMutableAttributedString, List <NewsCellView.Link> > CreateAttributedStringFromBlocks(UIFont font, UIColor primaryColor, IEnumerable <TextBlock> blocks)
        {
            var attributedString = new NSMutableAttributedString();
            var links            = new List <NewsCellView.Link>();

            nint lengthCounter = 0;
            int  i             = 0;

            CoreText.CTFont ctFont;

            try
            {
                ctFont = new CoreText.CTFont(font.FamilyName, font.PointSize);
            }
            catch
            {
                ctFont = CGFont.CreateWithFontName(font.Name).ToCTFont(font.PointSize);
            }

            foreach (var b in blocks)
            {
                UIColor color = null;
                if (b.Tapped != null)
                {
                    color = LinkColor;
                }

                color = color ?? primaryColor;

                var str = new NSAttributedString(b.Value, new CoreText.CTStringAttributes()
                {
                    ForegroundColor = color.CGColor, Font = ctFont
                });
                attributedString.Append(str);
                var strLength = str.Length;

                if (b.Tapped != null)
                {
                    var weakTapped = new WeakReference <Action>(b.Tapped);
                    links.Add(new NewsCellView.Link {
                        Range = new NSRange(lengthCounter, strLength), Callback = () => weakTapped.Get()?.Invoke(), Id = i++
                    });
                }

                lengthCounter += strLength;
            }

            return(new Tuple <NSMutableAttributedString, List <NewsCellView.Link> >(attributedString, links));
        }
Exemple #10
0
        public void GetBoundingRect_WithEmptyGlyphs()
        {
            if (!PlatformHelper.CheckSystemVersion(10, 13))
            {
                return;
            }

            CGFont cgFont = CGFont.CreateWithFontName("Arial");

            ushort [] glyphs = new ushort [] {};

            CTFont ctFont = new CTFont(cgFont, 14, new CTFontDescriptor("Arial", 14));
            NSFont nsFont = NSFont.FromCTFont(ctFont);

            Assert.Throws <ArgumentException> (() => nsFont.GetBoundingRects(glyphs));
            Assert.Throws <ArgumentException> (() => nsFont.GetAdvancements(glyphs));
        }
Exemple #11
0
        public override void Draw(RectangleF rect)
        {
            base.Draw(rect);

            using (var context = UIGraphics.GetCurrentContext()) {
                UIBezierPath mainAxis = UIBezierPath.FromRoundedRect(new RectangleF(xAxisMargin, 0.0f, 2.0f, rect.Height), 2.0f);
                UIColor.FromRGB(203, 203, 203).SetFill();
                mainAxis.Fill();

                float sepInterval = Convert.ToSingle(Math.Floor((rect.Width - xAxisMargin - xTextMargin) / 5));
                for (int i = 1; i < 6; i++)
                {
                    var separatorAxis = new UIBezierPath();
                    separatorAxis.MoveTo(new PointF(xAxisMargin + sepInterval * i, 0));
                    separatorAxis.AddLineTo(new PointF(xAxisMargin + sepInterval * i, rect.Height - yAxisMargin));
                    UIColor.FromRGB(203, 203, 203).SetStroke();
                    separatorAxis.LineWidth = 1.0f;
                    separatorAxis.SetLineDash(new [] { 1.0f, 1.0f }, 1);
                    separatorAxis.Stroke();

                    var textLayer = new CATextLayer();
                    textLayer.ContentsScale = UIScreen.MainScreen.Scale;
                    CGFont font = CGFont.CreateWithFontName(LabelFont.Name);

                    if (font != null)
                    {
                        textLayer.SetFont(font);
                        font.Dispose();
                    }

                    textLayer.FontSize        = LabelFont.PointSize;
                    textLayer.AnchorPoint     = new PointF(0.5f, 0.0f);
                    textLayer.AlignmentMode   = CATextLayer.AlignmentCenter;
                    textLayer.BackgroundColor = UIColor.Clear.CGColor;
                    textLayer.ForegroundColor = LabelColor.CGColor;

                    SizeF size = ((NSString)"0000 h").StringSize(LabelFont);
                    textLayer.String   = "00 h";
                    textLayer.Bounds   = new RectangleF(0, 0, size.Width, size.Height);
                    textLayer.Position = new PointF(xAxisMargin + sepInterval * i, rect.Height - yAxisMargin + 5.0f);
                    Layer.AddSublayer(textLayer);
                    xAxisText [i - 1] = textLayer;
                }
            }
        }
Exemple #12
0
        private SliceLayer createSliceLayer()
        {
            var pieLayer = new SliceLayer();

            pieLayer.Frame = _pieView.Frame;
            var arcLayer = new CAShapeLayer();

            arcLayer.ZPosition   = 0;
            arcLayer.StrokeColor = null;
            pieLayer.AddSublayer(arcLayer);

            var textLayer = new CATextLayer();

            textLayer.ContentsScale = UIScreen.MainScreen.Scale;
            CGFont font = CGFont.CreateWithFontName(LabelFont.Name);

            if (font != null)
            {
                textLayer.SetFont(font);
                font.Dispose();
            }

            textLayer.FontSize        = LabelFont.PointSize;
            textLayer.AnchorPoint     = new CGPoint(0.5f, 0.5f);
            textLayer.AlignmentMode   = CATextLayer.AlignmentCenter;
            textLayer.BackgroundColor = UIColor.Clear.CGColor;
            textLayer.ForegroundColor = LabelColor.CGColor;

            if (LabelShadowColor != null)
            {
                textLayer.ShadowColor   = LabelShadowColor.CGColor;
                textLayer.ShadowOffset  = CGSize.Empty;
                textLayer.ShadowOpacity = 1.0f;
                textLayer.ShadowRadius  = 2.0f;
            }

            CGSize size = ((NSString)"0").StringSize(LabelFont);

            textLayer.Frame    = new CGRect(new CGPoint(0, 0), size);
            textLayer.Position = new CGPoint(_pieCenter.X + LabelRadius * (nfloat)Math.Cos(0), _pieCenter.Y + LabelRadius * (nfloat)Math.Sin(0));
            pieLayer.AddSublayer(textLayer);
            layerPool.Add(pieLayer);
            return(pieLayer);
        }
Exemple #13
0
        public void GetBoundingRect_SmokeTest()
        {
            CGFont cgFont = CGFont.CreateWithFontName("Arial");

            ushort [] glyphs = new ushort [5];
            for (int i = 0; i < 5; ++i)
            {
                glyphs[i] = cgFont.GetGlyphWithGlyphName("Hello"[i].ToString());
            }

            CTFont ctFont = new CTFont(cgFont, 14, new CTFontDescriptor("Arial", 14));
            NSFont nsFont = NSFont.FromCTFont(ctFont);

            var bounding    = nsFont.GetBoundingRects(glyphs);
            var advancement = nsFont.GetAdvancements(glyphs);

            Assert.AreEqual(5, bounding.Length);
            Assert.AreEqual(5, advancement.Length);
        }
        void DrawTextLine(RTRTextLine textLine, CALayer layer, RTRResultStabilityStatus progress)
        {
            var topLeft     = ScaledPoint(textLine.Quadrangle[0] as NSValue);
            var bottomLeft  = ScaledPoint(textLine.Quadrangle[1] as NSValue);
            var bottomRight = ScaledPoint(textLine.Quadrangle[2] as NSValue);
            var topRight    = ScaledPoint(textLine.Quadrangle[3] as NSValue);

            DrawQuadrangle(topLeft, bottomLeft, bottomRight, topRight, layer, progress);
            var recognizedString = textLine.Text;

            var textLayer  = new CATextLayer();
            var textWidth  = DistanceBetween(topLeft, topRight);
            var textHeight = DistanceBetween(topLeft, bottomLeft);

            var rectForTextLayer = new CGRect(bottomLeft.X, bottomLeft.Y, textWidth, textHeight);

            // Selecting the initial font size by rectangle
            var textFont = GetFont(recognizedString, rectForTextLayer);

            textLayer.SetFont(CGFont.CreateWithFontName(textFont.FontDescriptor.Name));
            textLayer.FontSize        = textFont.PointSize;
            textLayer.ForegroundColor = ProgressColor(progress).CGColor;
            textLayer.AlignmentMode   = CATextLayer.AlignmentCenter;
            textLayer.String          = recognizedString;
            textLayer.Frame           = rectForTextLayer;

            // Rotate the text layer
            var angle = (float)Math.Asin((bottomRight.Y - bottomLeft.Y) / DistanceBetween(bottomLeft, bottomRight));

            textLayer.AnchorPoint = new CGPoint(0, 0);
            textLayer.Position    = bottomLeft;
            //textLayer.Transform = new CATransform3DRotate(CATransform3DIdentity, angle, 0, 0, 1);
            textLayer.Transform = CATransform3D.MakeRotation(angle, 0, 0, 1);

            layer.AddSublayer(textLayer);
        }
Exemple #15
0
        protected INativeObject GetINativeInstance(Type t)
        {
            var ctor = t.GetConstructor(Type.EmptyTypes);

            if ((ctor != null) && !ctor.IsAbstract)
            {
                return(ctor.Invoke(null) as INativeObject);
            }

            if (!NativeObjectInterfaceType.IsAssignableFrom(t))
            {
                throw new ArgumentException("t");
            }
            switch (t.Name)
            {
            case "CFAllocator":
                return(CFAllocator.SystemDefault);

            case "CFBundle":
                var bundles = CFBundle.GetAll();
                if (bundles.Length > 0)
                {
                    return(bundles [0]);
                }
                else
                {
                    throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
                }

            case "CFNotificationCenter":
                return(CFNotificationCenter.Darwin);

            case "CFReadStream":
            case "CFStream":
                CFReadStream  readStream;
                CFWriteStream writeStream;
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(readStream);

            case "CFWriteStream":
                CFStream.CreatePairWithSocketToHost("www.google.com", 80, out readStream, out writeStream);
                return(writeStream);

            case "CFUrl":
                return(CFUrl.FromFile("/etc"));

            case "CFPropertyList":
                return(CFPropertyList.FromData(NSData.FromString("<string>data</string>")).PropertyList);

            case "DispatchData":
                return(DispatchData.FromByteBuffer(new byte [] { 1, 2, 3, 4 }));

            case "AudioFile":
                var path = Path.GetFullPath("1.caf");
                var af   = AudioFile.Open(CFUrl.FromFile(path), AudioFilePermission.Read, AudioFileType.CAF);
                return(af);

            case "CFHTTPMessage":
                return(CFHTTPMessage.CreateEmpty(false));

            case "CFMutableString":
                return(new CFMutableString("xamarin"));

            case "CGBitmapContext":
                byte[] data = new byte [400];
                using (CGColorSpace space = CGColorSpace.CreateDeviceRGB()) {
                    return(new CGBitmapContext(data, 10, 10, 8, 40, space, CGBitmapFlags.PremultipliedLast));
                }

            case "CGContextPDF":
                var filename = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments) + "/t.pdf";
                using (var url = new NSUrl(filename))
                    return(new CGContextPDF(url));

            case "CGColorConversionInfo":
                var cci = new GColorConversionInfoTriple()
                {
                    Space     = CGColorSpace.CreateGenericRgb(),
                    Intent    = CGColorRenderingIntent.Default,
                    Transform = CGColorConversionInfoTransformType.ApplySpace
                };
                return(new CGColorConversionInfo((NSDictionary)null, cci, cci, cci));

            case "CGDataConsumer":
                using (NSMutableData destData = new NSMutableData()) {
                    return(new CGDataConsumer(destData));
                }

            case "CGDataProvider":
                filename = "xamarin1.png";
                return(new CGDataProvider(filename));

            case "CGFont":
                return(CGFont.CreateWithFontName("Courier New"));

            case "CGPattern":
                return(new CGPattern(
                           new RectangleF(0, 0, 16, 16),
                           CGAffineTransform.MakeIdentity(),
                           16, 16,
                           CGPatternTiling.NoDistortion,
                           true,
                           (cgc) => {}));

            case "CMBufferQueue":
                return(CMBufferQueue.CreateUnsorted(2));

            case "CTFont":
                CTFontDescriptorAttributes fda = new CTFontDescriptorAttributes()
                {
                    FamilyName = "Courier",
                    StyleName  = "Bold",
                    Size       = 16.0f
                };
                using (var fd = new CTFontDescriptor(fda))
                    return(new CTFont(fd, 10));

            case "CTFontCollection":
                return(new CTFontCollection(new CTFontCollectionOptions()));

            case "CTFontDescriptor":
                fda = new CTFontDescriptorAttributes();
                return(new CTFontDescriptor(fda));

            case "CTTextTab":
                return(new CTTextTab(CTTextAlignment.Left, 2));

            case "CTTypesetter":
                return(new CTTypesetter(new NSAttributedString("Hello, world",
                                                               new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CTFrame":
                var framesetter = new CTFramesetter(new NSAttributedString("Hello, world",
                                                                           new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                }));
                var bPath = UIBezierPath.FromRect(new RectangleF(0, 0, 3, 3));
                return(framesetter.GetFrame(new NSRange(0, 0), bPath.CGPath, null));

            case "CTFramesetter":
                return(new CTFramesetter(new NSAttributedString("Hello, world",
                                                                new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CTGlyphInfo":
                return(new CTGlyphInfo("copyright", new CTFont("ArialMY", 24), "Foo"));

            case "CTLine":
                return(new CTLine(new NSAttributedString("Hello, world",
                                                         new CTStringAttributes()
                {
                    ForegroundColorFromContext = true,
                    Font = new CTFont("ArialMT", 24)
                })));

            case "CGImageDestination":
                var storage = new NSMutableData();
                return(CGImageDestination.Create(new CGDataConsumer(storage), "public.png", 1));

            case "CGImageMetadataTag":
                using (NSString name = new NSString("tagName"))
                    using (var value = new NSString("value"))
                        return(new CGImageMetadataTag(CGImageMetadataTagNamespaces.Exif, CGImageMetadataTagPrefixes.Exif, name, CGImageMetadataType.Default, value));

            case "CGImageSource":
                filename = "xamarin1.png";
                return(CGImageSource.FromUrl(NSUrl.FromFilename(filename)));

            case "SecPolicy":
                return(SecPolicy.CreateSslPolicy(false, null));

            case "SecIdentity":
                using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) {
                    NSDictionary[] array;
                    var            result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array);
                    if (result != SecStatusCode.Success)
                    {
                        throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result));
                    }
                    return(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle)));
                }

            case "SecTrust":
                X509Certificate x = new X509Certificate(mail_google_com);
                using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com"))
                    return(new SecTrust(x, policy));

            case "SslContext":
                return(new SslContext(SslProtocolSide.Client, SslConnectionType.Stream));

            case "UIFontFeature":
                return(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers));

            case "NetworkReachability":
                return(new NetworkReachability(IPAddress.Loopback, null));

            case "VTCompressionSession":
            case "VTSession":
                return(VTCompressionSession.Create(1024, 768, CMVideoCodecType.H264, (sourceFrame, status, flags, buffer) => { }, null, (CVPixelBufferAttributes)null));

            case "VTFrameSilo":
                return(VTFrameSilo.Create());

            case "VTMultiPassStorage":
                return(VTMultiPassStorage.Create());

            case "CFString":
                return(new CFString("test"));

            case "DispatchBlock":
                return(new DispatchBlock(() => { }));

            case "DispatchQueue":
                return(new DispatchQueue("com.example.subsystem.taskXYZ"));

            case "DispatchGroup":
                return(DispatchGroup.Create());

            case "CGColorSpace":
                return(CGColorSpace.CreateDeviceCmyk());

            case "CGGradient":
                CGColor[] cArray = { UIColor.Black.CGColor, UIColor.Clear.CGColor, UIColor.Blue.CGColor };
                return(new CGGradient(null, cArray));

            case "CGImage":
                filename = "xamarin1.png";
                using (var dp = new CGDataProvider(filename))
                    return(CGImage.FromPNG(dp, null, false, CGColorRenderingIntent.Default));

            case "CGColor":
                return(UIColor.Black.CGColor);

            case "CMClock":
                return(CMClock.HostTimeClock);

            case "CMTimebase":
                return(new CMTimebase(CMClock.HostTimeClock));

            case "CVPixelBufferPool":
                return(new CVPixelBufferPool(
                           new CVPixelBufferPoolSettings(),
                           new CVPixelBufferAttributes(CVPixelFormatType.CV24RGB, 100, 50)
                           ));

            case "SecCertificate":
                using (var cdata = NSData.FromArray(mail_google_com))
                    return(new SecCertificate(cdata));

            case "SecCertificate2":
                using (var cdata = NSData.FromArray(mail_google_com))
                    return(new SecCertificate2(new SecCertificate(cdata)));

            case "SecTrust2":
                X509Certificate x2 = new X509Certificate(mail_google_com);
                using (var policy = SecPolicy.CreateSslPolicy(true, "mail.google.com"))
                    return(new SecTrust2(new SecTrust(x2, policy)));

            case "SecIdentity2":
                using (var options = NSDictionary.FromObjectAndKey(new NSString("farscape"), SecImportExport.Passphrase)) {
                    NSDictionary[] array;
                    var            result = SecImportExport.ImportPkcs12(farscape_pfx, options, out array);
                    if (result != SecStatusCode.Success)
                    {
                        throw new InvalidOperationException(string.Format("Could not create the new instance for type {0} due to {1}.", t.Name, result));
                    }
                    return(new SecIdentity2(new SecIdentity(array [0].LowlevelObjectForKey(SecImportExport.Identity.Handle))));
                }

            case "SecKey":
                SecKey private_key;
                SecKey public_key;
                using (var record = new SecRecord(SecKind.Key)) {
                    record.KeyType       = SecKeyType.RSA;
                    record.KeySizeInBits = 512;                     // it's not a performance test :)
                    SecKey.GenerateKeyPair(record.ToDictionary(), out public_key, out private_key);
                    return(private_key);
                }

            case "SecAccessControl":
                return(new SecAccessControl(SecAccessible.WhenPasscodeSetThisDeviceOnly));

            default:
                throw new InvalidOperationException(string.Format("Could not create the new instance for type {0}.", t.Name));
            }
        }
Exemple #16
0
 public void CreateWithFontName()
 {
     Assert.Null(CGFont.CreateWithFontName(null), "CreateWithFontName");
 }
        public static void AddBadge(this UIBarButtonItem barButtonItem, string text, UIColor backgroundColor, UIColor textColor, bool filled = true, float fontSize = 11.0f)
        {
            if (string.IsNullOrEmpty(text))
            {
                return;
            }

            CGPoint offset = CGPoint.Empty;

            if (backgroundColor == null)
            {
                backgroundColor = UIColor.Red;
            }

            var font = UIFont.SystemFontOfSize(fontSize);

            if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0))
            {
                font = UIFont.MonospacedDigitSystemFontOfSize(fontSize, UIFontWeight.Regular);
            }

            var view   = barButtonItem.ValueForKey(new NSString(@"view")) as UIView;
            var bLayer = GetBadgeLayer(barButtonItem);

            bLayer?.RemoveFromSuperLayer();

            var badgeSize = text.StringSize(font);

            var height = badgeSize.Height;
            var width  = badgeSize.Width + 2; /* padding */

            //make sure we have at least a circle
            if (width < height)
            {
                width = height;
            }

            //x position is offset from right-hand side
            var x = view.Frame.Width - width + offset.X;

            var badgeFrame = new CGRect(new CGPoint(x: x, y: offset.Y), size: new CGSize(width: width, height: height));

            bLayer = new CAShapeLayer();
            DrawRoundedRect(bLayer, badgeFrame, 7.0f, backgroundColor, filled);
            view.Layer.AddSublayer(bLayer);

            // Initialiaze Badge's label
            var label = new CATextLayer
            {
                String            = text,
                TextAlignmentMode = CATextLayerAlignmentMode.Center,
                FontSize          = font.PointSize,
                Frame             = badgeFrame,
                ForegroundColor   = filled ? textColor.CGColor : UIColor.White.CGColor,
                BackgroundColor   = UIColor.Clear.CGColor,
                ContentsScale     = UIScreen.MainScreen.Scale
            };

            label.SetFont(CGFont.CreateWithFontName(font.Name));
            bLayer.AddSublayer(label);

            // Save Badge as UIBarButtonItem property
            objc_setAssociatedObject(barButtonItem.Handle, BadgeKey.Handle, bLayer.Handle, AssociationPolicy.RETAIN_NONATOMIC);
        }
        internal unsafe static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions, string typefaceKey)
        {
            if (string.IsNullOrEmpty(typefaceKey))
            {
                typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
            }

            var descriptor = UIFont.FromName(familyName, 20.0f).FontDescriptor;

            UIFontDescriptorSymbolicTraits traits = 0;

            if (fontResolvingOptions.IsItalic)
            {
                traits |= UIFontDescriptorSymbolicTraits.Italic;
            }

            if (fontResolvingOptions.IsBold)
            {
                traits |= UIFontDescriptorSymbolicTraits.Bold;
            }

            var uifont = UIFont.FromDescriptor(descriptor.CreateWithTraits(traits), 20.0f);
            var cgFont = CGFont.CreateWithFontName(uifont.Name);

            IntPtr tags       = CGFontCopyTableTags(cgFont.Handle);
            nint   tableCount = CFArrayGetCount(tags);
            nint   totalSize  = sizeof(FontHeader) + sizeof(TableEntry) * tableCount;

            for (int index = 0; index < tableCount; ++index)
            {
                nint tableSize = 0;

                int aTag = (int)CFArrayGetValueAtIndex(tags, index);

                IntPtr tableDataRef = CGFontCopyTableForTag(cgFont.Handle, aTag);

                if (tableDataRef != IntPtr.Zero)
                {
                    tableSize = CFDataGetLength(tableDataRef);
                    CFRelease(tableDataRef);
                }

                totalSize += (tableSize + 3) & ~3;
            }

            var data = new byte[totalSize];

            fixed(byte *dataStart = data)
            {
                byte *dataPtr = dataStart;

                UInt16 entrySelector = 0;
                UInt16 searchRange   = 1;

                while (searchRange < tableCount >> 1)
                {
                    entrySelector++;
                    searchRange <<= 1;
                }
                searchRange <<= 4;

                UInt16 rangeShift = (UInt16)((tableCount << 4) - searchRange);

                FontHeader *offsetTable = (FontHeader *)dataPtr;

                offsetTable->fVersion       = (Int32)SwapBytes((UInt16)1);
                offsetTable->fNumTables     = SwapBytes((UInt16)tableCount);
                offsetTable->fSearchRange   = SwapBytes((UInt16)searchRange);
                offsetTable->fEntrySelector = SwapBytes((UInt16)entrySelector);
                offsetTable->fRangeShift    = SwapBytes((UInt16)rangeShift);
                dataPtr += sizeof(FontHeader);

                TableEntry *entry = (TableEntry *)dataPtr;

                dataPtr += sizeof(TableEntry) * tableCount;

                for (int index = 0; index < tableCount; ++index)
                {
                    int aTag = (int)CFArrayGetValueAtIndex(tags, index);

                    IntPtr tableDataRef = CGFontCopyTableForTag(cgFont.Handle, aTag);

                    nint tableSize = 0;

                    if (tableDataRef != IntPtr.Zero)
                    {
                        tableSize = CFDataGetLength(tableDataRef);
                        Buffer.MemoryCopy((byte *)CFDataGetBytePtr(tableDataRef), dataPtr, tableSize, tableSize);
                        entry->fTag      = SwapBytes((UInt32)aTag);
                        entry->fCheckSum = SwapBytes(CalcTableCheckSum((UInt32 *)dataPtr, tableSize));
                        UInt32 offset = (UInt32)(dataPtr - dataStart);
                        entry->fOffset = SwapBytes((UInt32)offset);
                        entry->fLength = SwapBytes((UInt32)tableSize);
                        CFRelease(tableDataRef);
                    }

                    dataPtr += (tableSize + 3) & ~3;
                    ++entry;
                }
            }

            var fontSource = XFontSource.GetOrCreateFrom(typefaceKey, data);

            return(fontSource);
        }
Exemple #19
0
        private BarLayer CreateBarLayer(float barHeight)
        {
            var barLayer = new BarLayer()
            {
                ZPosition   = 0,
                BorderColor = UIColor.White.CGColor,
                AnchorPoint = new PointF(0.0f, 0.5f),
                Frame       = new RectangleF(0, 0, Bounds.Width, barHeight)
            };

            var mainBar = new CALayer();

            mainBar.AnchorPoint     = new PointF(0.0f, 0.0f);
            mainBar.Bounds          = new RectangleF(0, 0, Bounds.Width - xAxisMargin - xTextMargin, barHeight);
            mainBar.Position        = new PointF(xAxisMargin, 0);
            mainBar.BackgroundColor = MainBarColor.CGColor;
            mainBar.SetValueForKeyPath(new NSNumber(minBarScale), new NSString("transform.scale.x"));
            barLayer.AddSublayer(mainBar);

            var secondaryBar = new CALayer();

            secondaryBar.AnchorPoint     = new PointF(0.0f, 0.0f);
            secondaryBar.Bounds          = new RectangleF(0, 0, Bounds.Width - xAxisMargin - xTextMargin, barHeight);
            secondaryBar.Position        = new PointF(xAxisMargin, 0);
            secondaryBar.BackgroundColor = SecondaryBarColor.CGColor;
            secondaryBar.SetValueForKeyPath(new NSNumber(minBarScale), new NSString("transform.scale.x"));
            barLayer.AddSublayer(secondaryBar);

            var emptyBar = new CALayer();

            emptyBar.AnchorPoint     = new PointF(0.0f, 0.0f);
            emptyBar.Bounds          = new RectangleF(0, 0, 2.0f, barHeight);
            emptyBar.Position        = new PointF(xAxisMargin, 0);
            emptyBar.BackgroundColor = UIColor.Gray.CGColor;
            barLayer.AddSublayer(emptyBar);

            CGFont font = CGFont.CreateWithFontName(LabelFont.Name);
            SizeF  size = ((NSString)"00.00:00").StringSize(LabelFont);

            var textLayer = new CATextLayer()
            {
                ContentsScale   = UIScreen.MainScreen.Scale,
                FontSize        = 10.0f,
                AnchorPoint     = new PointF(0.0f, 0.5f),
                AlignmentMode   = CATextLayer.AlignmentLeft,
                BackgroundColor = UIColor.Clear.CGColor,
                ForegroundColor = LabelColor.CGColor
            };

            barLayer.AddSublayer(textLayer);

            var timeTextLayer = new CATextLayer()
            {
                ContentsScale   = UIScreen.MainScreen.Scale,
                FontSize        = 10.0f,
                AnchorPoint     = new PointF(0.0f, 0.5f),
                AlignmentMode   = CATextLayer.AlignmentLeft,
                BackgroundColor = UIColor.Clear.CGColor,
                ForegroundColor = SecondaryBarColor.CGColor
            };

            barLayer.AddSublayer(timeTextLayer);

            if (font != null)
            {
                textLayer.SetFont(font);
                timeTextLayer.SetFont(font);
                font.Dispose();
            }

            CATransaction.DisableActions = true;
            textLayer.Bounds             = new RectangleF(new PointF(0, 0), size);
            textLayer.Position           = mainBar.Position;
            timeTextLayer.Bounds         = new RectangleF(new PointF(0, 0), size);
            timeTextLayer.Position       = new PointF(mainBar.Position.X + 5.0f, mainBar.Position.Y);
            CATransaction.DisableActions = false;

            return(barLayer);
        }
Exemple #20
0
        private CTFont GetFontFromCache(string key, string name, float size)
        {
            CTFont font;

            lock (_fontCache)
            {
                if (!_fontCache.TryGetValue(key, out font))
                {
                    /*if (name != null && MTFontRegistry.Instance.IsCustomFont(name))
                     * {
                     *  var coreGraphicsFont = MTFontRegistry.Instance.GetCustomFont(name);
                     *  if (coreGraphicsFont != null)
                     *  {
                     *      font = new CTFont(coreGraphicsFont, size, CGAffineTransform.MakeIdentity());
                     *  }
                     * }
                     * else
                     * {*/
                    var fontStyle = GetFontStyleById(name);
                    if (fontStyle == null)
                    {
                        if (_systemFontName.Equals(name))
                        {
                            if (name.StartsWith(".", StringComparison.InvariantCultureIgnoreCase))
                            {
                                var cgfont = _systemFont ?? (_systemFont = CGFont.CreateWithFontName(name));
                                font = new CTFont(cgfont, size, CGAffineTransform.MakeIdentity());
                            }
                            else
                            {
                                font = new CTFont(name, size);
                            }
                        }
                        else if (_boldSystemFontName.Equals(name))
                        {
                            if (name.StartsWith(".", StringComparison.InvariantCultureIgnoreCase))
                            {
                                var cgfont = _boldSystemFont ?? (_boldSystemFont = CGFont.CreateWithFontName(name));
                                font = new CTFont(cgfont, size, CGAffineTransform.MakeIdentity());
                            }
                            else
                            {
                                font = new CTFont(name, size);
                            }
                        }
                        else
                        {
                            fontStyle = GetDefaultFontStyle();
                        }
                    }

                    if (font == null)
                    {
                        font = new CTFont(fontStyle.Id, size);
                    }
                    //}

                    if (font == null)
                    {
                        return(LoadFont("ArialMT", size));
                    }

                    _fontCache[key] = font;
                }
            }

            return(font);
        }