private void drawString(IBrush brush, float x, float y) { using (NSMutableAttributedString str = new NSMutableAttributedString(_text)) { NSRange range = new NSRange(0, _text.Length); var foreColor = brush.Color; using (CGColor color = new CGColor(foreColor.R / 255f, foreColor.G / 255f, foreColor.B / 255f, foreColor.A / 255f)) { str.SetAttributes(new CTStringAttributes { Font = ((IOSFont)_config.Font).InnerFont, ForegroundColor = color }, range); using (CTFramesetter frameSetter = new CTFramesetter(str)) using (CGPath path = new CGPath()) { NSRange fitRange; CGSize size = frameSetter.SuggestFrameSize(range, null, new CGSize(_maxWidth, _height), out fitRange); path.AddRect(new CGRect(x, y, size.Width, size.Height)); using (var frame = frameSetter.GetFrame(fitRange, path, null)) { frame.Draw(_context); } } } } }
public void DrawString(string s, float x, float y) { if (string.IsNullOrEmpty(s)) { return; } using (var astr = new NSMutableAttributedString(s)) { astr.AddAttributes(_attrs, new NSRange(0, s.Length)); using (var fs = new CTFramesetter(astr)) { using (var path = new CGPath()) { var h = _lastFont.Size * 2; path.AddRect(new NativeRect(0, 0, s.Length * h, h)); using (var f = fs.GetFrame(new NSRange(0, 0), path, null)) { var line = f.GetLines()[0]; NativeValue a, d, l; line.GetTypographicBounds(out a, out d, out l); _c.SaveState(); _c.TranslateCTM(x, h + y - d); _c.ScaleCTM(1, -1); f.Draw(_c); _c.RestoreState(); } } } } }
public SizeF MeasureString(string text, Alignment alignment, int maxWidth = int.MaxValue) { //todo: support alignment var key = new TextMeasureKey(text, InnerFont, maxWidth); return(_measurements.GetOrAdd(key, k => { using (NSMutableAttributedString str = new NSMutableAttributedString(text)) { NSRange range = new NSRange(0, k.Text.Length); str.SetAttributes(new CTStringAttributes { Font = k.Font, }, range); using (CTFramesetter frameSetter = new CTFramesetter(str)) { NSRange fitRange; CGSize size = frameSetter.SuggestFrameSize(range, null, new CGSize(k.MaxWidth, float.MaxValue), out fitRange); return new SizeF((float)size.Width, (float)size.Height); } } })); }
partial void MeasureStringImp(string text, Font font, StringFormat format, SizeF frameSz, ref SizeF ret) { var attributedString = CreateAttributedString(text, font, format, null); using (var framesetter = new CTFramesetter(attributedString)) { NSRange fitRange; ret = framesetter.SuggestFrameSize(new NSRange(0, 0), null, frameSz.ToCGSize(), out fitRange).ToSizeF(); } }
void TextChanged () { SetNeedsDisplay (); ClearPreviousLayoutInformation (); attributedString = new NSAttributedString (Text, attributes); framesetter = new CTFramesetter (attributedString); UIBezierPath path = UIBezierPath.FromRect (Bounds); frame = framesetter.GetFrame (new NSRange (0, 0), path.CGPath, null); }
public override void Draw(CoreGraphics.CGRect rect) { base.Draw(rect); if (_path == null) { return; } using (CGContext g = UIGraphics.GetCurrentContext()) { //set up drawing attributes g.SetLineWidth(1); UIColor.Clear.SetFill(); UIColor.Clear.SetStroke(); var attrString = new NSMutableAttributedString(" "); if (_text != null) { attrString = new NSMutableAttributedString(_text); } // We'll Set the justification to center so it'll // print the number in the center of the erect CTParagraphStyle alignStyle = new CTParagraphStyle(new CTParagraphStyleSettings { Alignment = _textAligment //CTTextAlignment.Left }); // Calculate the range of the attributed string NSRange stringRange = new NSRange(0, attrString.Length); var font = new CTFont(_fontName, _fontSize); // Add style attributes to the attributed string attrString.AddAttributes(new CTStringAttributes { Font = font, ParagraphStyle = alignStyle, ForegroundColor = Foreground.CGColor }, stringRange); // Create a container for the attributed string using (var framesetter = new CTFramesetter(attrString)) { using (var frame = framesetter.GetFrame(stringRange, _path, null)) { g.SaveState(); g.TranslateCTM(0, TextHeight); g.ScaleCTM(1, -1); //g.RotateCTM (0.2f ); frame.Draw(g); g.RestoreState(); } } } }
void ClearPreviousLayoutInformation () { if (framesetter != null) { framesetter.Dispose (); framesetter = null; } if (frame != null) { frame.Dispose (); frame = null; } }
[Test] // #4677 public void GetPathTest() { using (var framesetter = new CTFramesetter(new NSAttributedString("Testing, testing, 1, 2, 3..."))) { using (var frame = framesetter.GetFrame(new NSRange(0, 0), new CGPath(), null)) { using (var f = frame.GetPath()) { } using (var f = frame.GetPath()) { Console.WriteLine(f.BoundingBox); } } } }
public void CTTypesetterCreateTest() { TestRuntime.AssertXcodeVersion(10, 0); using (var framesetter = new CTFramesetter(new NSAttributedString("Testing, testing, 1, 2, 3..."))) using (var type = framesetter.GetTypesetter()) using (var newFrame = CTFramesetter.Create(type)) { Assert.NotNull(type, "Create"); var type2 = newFrame.GetTypesetter(); Assert.NotNull(type, "type2"); Assert.AreEqual(type.Handle, type2.Handle, "Same typesetter"); } }
void TextChanged() { SetNeedsDisplay(); ClearPreviousLayoutInformation(); attributedString = new NSAttributedString(Text, attributes); framesetter = new CTFramesetter(attributedString); UIBezierPath path = UIBezierPath.FromRect(Bounds); frame = framesetter.GetFrame(new NSRange(0, 0), path.CGPath, null); }
private void DrawTemperatureNumber(double degree, double increase) { using (var font = new CTFont("Verdana", 10)) using (var context = UIGraphics.GetCurrentContext()) { UIColor.Clear.SetFill(); CGRect erect = new CGRect(increase - 15, (.7 * sViewHeight) + 20, 30, 20); // Fill and stroke the the circle first so the // number will be drawn on top of the circle // using (var path = new CGPath()) { // path.AddEllipseInRect (erect); // context.AddPath (path); // context.DrawPath (CGPathDrawingMode.FillStroke); // } // Then draw the number 'on top of' the circle using (var path = new CGPath()) using (var attrString = new NSMutableAttributedString(degree.ToString())) { // We'll Set the justification to center so it'll // print the number in the center of the erect CTParagraphStyle alignStyle = new CTParagraphStyle(new CTParagraphStyleSettings { Alignment = CTTextAlignment.Center }); // Calculate the range of the attributed string NSRange stringRange = new NSRange(0, attrString.Length); // Add style attributes to the attributed string attrString.AddAttributes(new CTStringAttributes { Font = font, ParagraphStyle = alignStyle, ForegroundColor = UIColor.Red.CGColor }, stringRange); // Create a container for the attributed string using (var framesetter = new CTFramesetter(attrString)) { erect.Y = -erect.Y; path.AddRect(erect); using (var frame = framesetter.GetFrame(stringRange, path, null)) { context.SaveState(); context.TranslateCTM((nfloat)0, erect.Height); context.ScaleCTM(1, -1); frame.Draw(context); context.RestoreState(); } } } } }
public static RectangleF GetTextSize(CTFramesetter frameSetter, CGPath path) { var frame = frameSetter.GetFrame(new NSRange(0, 0), path, null); if (frame != null) { var textSize = GetTextSize(frame); frame.Dispose(); return(textSize); } return(new RectangleF(0, 0, 0, 0)); }
void ClearPreviousLayoutInformation() { if (framesetter != null) { framesetter.Dispose(); framesetter = null; } if (frame != null) { frame.Dispose(); frame = null; } }
static CTFrame CreateFrame(LayoutInfo li) { if (string.IsNullOrEmpty(li.Text)) { return(null); } using (CTFramesetter framesetter = new CTFramesetter(CreateAttributedString(li))) { CGPath path = new CGPath(); path.AddRect(new RectangleF(0, 0, li.Width ?? float.MaxValue, li.Height ?? float.MaxValue)); return(framesetter.GetFrame(new NSRange(0, li.Text.Length), path, null)); } }
static CTFrame CreateFrame(LayoutInfo li) { if (string.IsNullOrEmpty(li.Text)) { return(null); } using (CTFramesetter framesetter = new CTFramesetter(CreateAttributedString(li))) { CGPath path = new CGPath(); bool ellipsize = li.Width.HasValue && li.TextTrimming == TextTrimming.WordElipsis; path.AddRect(new CGRect(0, 0, li.Width.HasValue && !ellipsize ? li.Width.Value : float.MaxValue, li.Height ?? float.MaxValue)); return(framesetter.GetFrame(new NSRange(0, li.Text.Length), path, null)); } }
partial void DrawStringImp(string s, Font font, Brush brush, RectangleF frame, StringFormat format) { var attributedString = CreateAttributedString(s, font, format, brush); if (format != null && (format.horizontalAlignment != StringAlignment.Near || format.verticalAlignment != StringAlignment.Near)) { using (var framesetter = new CTFramesetter(attributedString)) { NSRange fitRange; var sz = framesetter.SuggestFrameSize(new NSRange(0, 0), null, frame.Size.ToCGSize(), out fitRange); RectangleF newFrame = new RectangleF(new PointF(), sz.ToSizeF()); if (format.horizontalAlignment == StringAlignment.Near) { newFrame.X = frame.X; } else if (format.horizontalAlignment == StringAlignment.Center) { newFrame.X = (float)(frame.Left + frame.Right - sz.Width) / 2; } else if (format.horizontalAlignment == StringAlignment.Far) { newFrame.X = (float)(frame.Right - sz.Width); } if (format.verticalAlignment == StringAlignment.Near) { newFrame.Y = frame.Y; } else if (format.verticalAlignment == StringAlignment.Center) { newFrame.Inflate(0, 1); newFrame.Y = (float)(frame.Top + frame.Bottom - sz.Height) / 2; } else if (format.verticalAlignment == StringAlignment.Far) { newFrame.Y = (float)(frame.Bottom - sz.Height); } attributedString.DrawString(newFrame.ToCGRect()); } } else { attributedString.DrawString(frame.ToCGRect()); } }
public void Runs() { using (var mas = new NSMutableAttributedString("Bonjour")) using (var rd = new CTRunDelegate(new MyOps())) { var sa = new CTStringAttributes() { RunDelegate = rd, }; mas.SetAttributes(sa, new NSRange(3, 3)); using (var fs = new CTFramesetter(mas)) { Assert.True(MyOps.Ascent, "Ascent called"); Assert.True(MyOps.Descent, "Descent called"); Assert.True(MyOps.Width, "Width called"); } } }
public SizeF MeasureString(string text, int maxWidth = int.MaxValue) { using (NSMutableAttributedString str = new NSMutableAttributedString(text)) { NSRange range = new NSRange(0, text.Length); str.SetAttributes(new CTStringAttributes { Font = InnerFont, }, range); using (CTFramesetter frameSetter = new CTFramesetter(str)) { NSRange fitRange; CGSize size = frameSetter.SuggestFrameSize(range, null, new CGSize(maxWidth, float.MaxValue), out fitRange); return(new SizeF((float)size.Width, (float)size.Height)); } } }
NativeSize StringSize(string str, int startIndex, int length) { if (str == null || length <= 0) { return(NativeSize.Empty); } using (var astr = new NSMutableAttributedString(str)) { astr.AddAttributes(attrs, new NSRange(startIndex, length)); using (var fs = new CTFramesetter(astr)) { using (var path = new CGPath()) { path.AddRect(new NativeRect(0, 0, 30000, attrs.Font.XHeightMetric * 10)); using (var f = fs.GetFrame(new NSRange(startIndex, length), path, null)) { var line = f.GetLines() [0]; NativeValue a, d, l; var tw = line.GetTypographicBounds(out a, out d, out l); return(new NativeSize((float)tw, (a + d) * 1.2f)); } } } } }
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)); } }
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 "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 "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 "CGColorConverter": var cvt = new CGColorConverterTriple () { Space = CGColorSpace.CreateGenericRgb (), Intent = CGColorRenderingIntent.Default, Transform = CGColorConverterTransformType.ApplySpace }; return new CGColorConverter (null, cvt, cvt, cvt); 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, CTFontOptions.Default); 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 ("Arial", 24) })); case "CTFrame": var framesetter = new CTFramesetter (new NSAttributedString ("Hello, world", new CTStringAttributes () { ForegroundColorFromContext = true, Font = new CTFont ("Arial", 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 ("Arial", 24) })); case "CTGlyphInfo": return new CTGlyphInfo ("Zapfino", new CTFont ("Arial", 24), "Foo"); case "CTLine": return new CTLine (new NSAttributedString ("Hello, world", new CTStringAttributes () { ForegroundColorFromContext = true, Font = new CTFont ("Arial", 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); #if !__TVOS__ 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 (); #endif case "CFString": return new CFString ("test"); case "DispatchQueue": return new DispatchQueue ("com.example.subsystem.taskXYZ"); case "DispatchGroup": return DispatchGroup.Create (); case "CGColorSpace": return CGColorSpace.CreateAcesCGLinear (); 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": CMClockError ce; CMClock clock = CMClock.CreateAudioClock (out ce); if (ce == CMClockError.None) return clock; throw new InvalidOperationException (string.Format ("Could not create the new instance for type {0}.", t.Name)); case "CMTimebase": clock = CMClock.CreateAudioClock (out ce); if (ce == CMClockError.None) { return new CMTimebase (clock); } throw new InvalidOperationException (string.Format ("Could not create the new instance for type {0}.", t.Name)); 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 "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)); } }
public override void Draw(CGRect rect) { var framesetter = new CTFramesetter(AttributedText); var path = new CGPath(); path.AddRect(new CGRect(0, 0, Bounds.Size.Width, Bounds.Size.Height)); var totalFrame = framesetter.GetFrame(new NSRange(0, 0), path, null); var context = UIGraphics.GetCurrentContext(); context.TextMatrix = CGAffineTransform.MakeIdentity(); context.TranslateCTM(0, Bounds.Size.Height); context.ScaleCTM(1.0f, -1.0f); var lines = totalFrame.GetLines(); var lineCount = lines.Length; var origins = new CGPoint[lineCount]; totalFrame.GetLineOrigins(new NSRange(0, 0), origins); for (var index = 0; index < lineCount; index++) { var line = lines[index]; foreach (var run in line.GetGlyphRuns()) { var attributes = run.GetAttributes(); var borderColor = attributes.Dictionary[RoundedBorders]; var backgroundColor = attributes.Dictionary[RoundedBackground]; if (backgroundColor == null && borderColor == null) { continue; } var x = line.GetOffsetForStringIndex(run.StringRange.Location, out var _) + whiteSpaceOffset; var y = origins[index].Y - (tokenHeight * 0.7); var tokenPath = UIBezierPath.FromRoundedRect(new CGRect( x: x, y: y, width: run.GetTypographicBounds(new NSRange(0, 0), out var _, out var _, out var _) - whiteSpaceOffset, height: tokenHeight ), tokenCornerRadius); context.AddPath(tokenPath.CGPath); if (backgroundColor != null) { var color = (UIColor)backgroundColor; context.SetFillColor(color.CGColor); context.DrawPath(CGPathDrawingMode.Fill); var circle = UIBezierPath.FromRoundedRect(new CGRect( x: x + circlePadding, y: y + circleYOffset, width: circleDiameter, height: circleDiameter ), circleRadius); context.AddPath(circle.CGPath); context.SetFillColor(color.ColorWithAlpha(1.0f).CGColor); context.DrawPath(CGPathDrawingMode.Fill); } else { var color = ((UIColor)borderColor).CGColor; context.SetStrokeColor(color); context.DrawPath(CGPathDrawingMode.Stroke); } } } path.Dispose(); totalFrame.Dispose(); framesetter.Dispose(); }
void drawLabel (CGContext ctx, CGRect rect, nfloat yCoord, nfloat xCoord, UITextAlignment alignment, string label, bool flipContext = true, bool centerVertical = false) { // Draw light the sunrise and Sunset labels at the ends of the light box using (UIColor fontColor = UIColor.White, shadowColor = UIColor.Black.ColorWithAlpha (0.1f)) { var fontAttributes = new UIFontAttributes (new UIFontFeature (CTFontFeatureNumberSpacing.Selector.ProportionalNumbers)); using (var desc = UIFont.SystemFontOfSize (fontSize).FontDescriptor.CreateWithAttributes (fontAttributes)) { using (UIFont font = UIFont.FromDescriptor (desc, fontSize)) { // calculating the range of our attributed string var range = new NSRange (0, label.Length); // set justification for text block using (var alignStyle = new NSMutableParagraphStyle { Alignment = alignment }) { // add stylistic attributes to out attributed string var stringAttributes = new UIStringAttributes { ForegroundColor = fontColor, Font = font, ParagraphStyle = alignStyle }; var target = new CGSize (float.MaxValue, float.MaxValue); NSRange fit; using (NSMutableAttributedString attrString = new NSMutableAttributedString (label, stringAttributes)) { //creating a container for out attributed string using (CTFramesetter framesetter = new CTFramesetter (attrString)) { CGSize frameSize = framesetter.SuggestFrameSize (range, null, target, out fit); if (alignment == UITextAlignment.Center) xCoord -= (frameSize.Width / 2); if (alignment == UITextAlignment.Right) xCoord -= frameSize.Width; // subtract the frameSize so the flipped context behaves as expected yCoord -= frameSize.Height; if (centerVertical) yCoord += (frameSize.Height / 2); var textRect = new CGRect (xCoord, yCoord, frameSize.Width, frameSize.Height); using (CGPath path = new CGPath ()) { path.AddRect (textRect); ctx.SetShadow (new CGSize (0.0f, 1.0f), 0.0f, shadowColor.CGColor); using (CTFrame frame = framesetter.GetFrame (range, path, null)) { if (flipContext) { ctx.SaveState (); ctx.TranslateCTM (0, rect.Height); ctx.ScaleCTM (1, -1); frame.Draw (ctx); ctx.RestoreState (); } else { frame.Draw (ctx); } } } } } } } } } }
void drawLabel(CGContext ctx, CGRect rect, nfloat yCoord, nfloat xCoord, CTTextAlignment alignment, UIColor color, string label, bool flipContext = true) { Console.WriteLine("Finish Draw code"); var attrString = new NSMutableAttributedString (label); var range = new NSRange (0, attrString.Length); var uiFont = UIFont.FromName("HelveticaNeue-Medium", range.Length > 1 ? 15 : 22); var font = new CTFont (uiFont.Name, uiFont.PointSize); //((uiFont.Name as NSString) as CFString, uiFont.pointSize, nil); var path = new CGPath (); var alignStyle = new CTParagraphStyle (new CTParagraphStyleSettings { Alignment = alignment }); var attributes = new CTStringAttributes { Font = font, ForegroundColor = color.CGColor, ParagraphStyle = alignStyle }; attrString.SetAttributes(attributes, new NSRange (0, attrString.Length)); var target = new CGSize (nfloat.MaxValue, nfloat.MaxValue); var fit = new NSRange (0, 0); var framesetter = new CTFramesetter (attrString); var frameSize = framesetter.SuggestFrameSize(range, null, target, out fit); var textRect = new CGRect (xCoord - (frameSize.Width / 2), yCoord - (frameSize.Height / 2), frameSize.Width, frameSize.Height); path.AddRect(textRect); var frame = framesetter.GetFrame(range, path, null); if (flipContext) { ctx.SaveState(); ctx.TranslateCTM(0, rect.Height); ctx.ScaleCTM(1, -1); frame.Draw(ctx); ctx.RestoreState(); } else { frame.Draw(ctx); } }
public SizeF GetStringSize( string value, string fontName, float fontSize, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) { float factor = 1; while (fontSize > 10) { fontSize /= 10; factor *= 10; } var path = new CGPath(); path.AddRect(new Drawing.RectangleF(0, 0, 512, 512)); path.CloseSubpath(); var attributedString = new NSMutableAttributedString(value); var attributes = new CTStringAttributes(); // Load the font var font = NativeFontService.Instance.LoadFont(fontName ?? SystemFontName, fontSize); attributes.Font = font; // Set the horizontal alignment var paragraphSettings = new CTParagraphStyleSettings(); switch (horizontalAlignment) { case HorizontalAlignment.Left: paragraphSettings.Alignment = CTTextAlignment.Left; break; case HorizontalAlignment.Center: paragraphSettings.Alignment = CTTextAlignment.Center; break; case HorizontalAlignment.Right: paragraphSettings.Alignment = CTTextAlignment.Right; break; case HorizontalAlignment.Justified: paragraphSettings.Alignment = CTTextAlignment.Justified; break; } var paragraphStyle = new CTParagraphStyle(paragraphSettings); attributes.ParagraphStyle = paragraphStyle; // Set the attributes for the complete length of the string attributedString.SetAttributes(attributes, new NSRange(0, value.Length)); // Create the frame setter with the attributed string. var frameSetter = new CTFramesetter(attributedString); var textBounds = GetTextSize(frameSetter, path); //Logger.Debug("{0} {1}",vSize,aString); frameSetter.Dispose(); attributedString.Dispose(); paragraphStyle.Dispose(); //font.Dispose(); path.Dispose(); textBounds.Width *= factor; textBounds.Height *= factor; //size.Width = Math.Ceiling(vSize.Width); //size.Height = Math.Ceiling(vSize.Height); return(textBounds.Size); }
public SizeF GetStringSize(string aString, string aFontName, float aFontSize, HorizontalAlignment aHorizontalAlignment, VerticalAlignment aVerticalAlignment) { var fontSize = aFontSize; float factor = 1; while (fontSize > 10) { fontSize /= 10; factor *= 10; } var vPath = new CGPath(); vPath.AddRect(new CGRect(0, 0, 512, 512)); vPath.CloseSubpath(); var vAttributedString = new NSMutableAttributedString(aString); var vAttributes = new CTStringAttributes(); // Load the font var vFont = NativeFontService.Instance.LoadFont(aFontName ?? _systemFontName, (float)fontSize); vAttributes.Font = vFont; // Set the horizontal alignment var vParagraphSettings = new CTParagraphStyleSettings(); switch (aHorizontalAlignment) { case HorizontalAlignment.Left: vParagraphSettings.Alignment = CTTextAlignment.Left; break; case HorizontalAlignment.Center: vParagraphSettings.Alignment = CTTextAlignment.Center; break; case HorizontalAlignment.Right: vParagraphSettings.Alignment = CTTextAlignment.Right; break; case HorizontalAlignment.Justified: vParagraphSettings.Alignment = CTTextAlignment.Justified; break; } var vParagraphStyle = new CTParagraphStyle(vParagraphSettings); vAttributes.ParagraphStyle = vParagraphStyle; // Set the attributes for the complete length of the string vAttributedString.SetAttributes(vAttributes, new NSRange(0, aString.Length)); // Create the framesetter with the attributed string. var vFrameSetter = new CTFramesetter(vAttributedString); var textBounds = GetTextSize(vFrameSetter, vPath); //Logger.Debug("{0} {1}",vSize,aString); vFrameSetter.Dispose(); vAttributedString.Dispose(); vParagraphStyle.Dispose(); //vFont.Dispose(); vPath.Dispose(); textBounds.Width *= factor; textBounds.Height *= factor; //vSize.Width = Math.Ceiling(vSize.Width); //vSize.Height = Math.Ceiling(vSize.Height); return(textBounds.Size); }
NativeSize StringSize (string str, int startIndex, int length) { if (str == null || length <= 0) return NativeSize.Empty; using (var astr = new NSMutableAttributedString (str)) { astr.AddAttributes (attrs, new NSRange (startIndex, length)); using (var fs = new CTFramesetter (astr)) { using (var path = new CGPath ()) { path.AddRect (new NativeRect (0, 0, 30000, attrs.Font.XHeightMetric * 10)); using (var f = fs.GetFrame (new NSRange (startIndex, length), path, null)) { var line = f.GetLines () [0]; NativeValue a, d, l; var tw = line.GetTypographicBounds (out a, out d, out l); return new NativeSize ((float)tw, (a + d) * 1.2f); } } } } }
public void DrawString (string s, float x, float y) { if (string.IsNullOrEmpty (s)) return; using (var astr = new NSMutableAttributedString (s)) { astr.AddAttributes (_attrs, new NSRange (0, s.Length)); using (var fs = new CTFramesetter (astr)) { using (var path = new CGPath ()) { var h = _lastFont.Size * 2; path.AddRect (new NativeRect (0, 0, s.Length * h, h)); using (var f = fs.GetFrame (new NSRange (0, 0), path, null)) { var line = f.GetLines () [0]; NativeValue a, d, l; line.GetTypographicBounds (out a, out d, out l); _c.SaveState (); _c.TranslateCTM (x, h + y - d); _c.ScaleCTM (1, -1); f.Draw (_c); _c.RestoreState (); } } } } // var c = _color; // SetColor (Colors.Black); // DrawRect (x, y, 100, _lastFont.Size, 1); // SetColor (c); }
void drawLabel(CGContext ctx, CGRect rect, nfloat yCoord, nfloat xCoord, UITextAlignment alignment, string label, bool flipContext = true, bool centerVertical = false) { // Draw light the sunrise and Sunset labels at the ends of the light box using (UIColor fontColor = UIColor.White, shadowColor = UIColor.Black.ColorWithAlpha(0.1f)) { var fontAttributes = new UIFontAttributes(new UIFontFeature(CTFontFeatureNumberSpacing.Selector.ProportionalNumbers)); using (var desc = UIFont.SystemFontOfSize(fontSize).FontDescriptor.CreateWithAttributes(fontAttributes)) { using (UIFont font = UIFont.FromDescriptor(desc, fontSize)) { // calculating the range of our attributed string var range = new NSRange(0, label.Length); // set justification for text block using (var alignStyle = new NSMutableParagraphStyle { Alignment = alignment }) { // add stylistic attributes to out attributed string var stringAttributes = new UIStringAttributes { ForegroundColor = fontColor, Font = font, ParagraphStyle = alignStyle }; var target = new CGSize(float.MaxValue, float.MaxValue); NSRange fit; using (NSMutableAttributedString attrString = new NSMutableAttributedString(label, stringAttributes)) { //creating a container for out attributed string using (CTFramesetter framesetter = new CTFramesetter(attrString)) { CGSize frameSize = framesetter.SuggestFrameSize(range, null, target, out fit); if (alignment == UITextAlignment.Center) { xCoord -= (frameSize.Width / 2); } if (alignment == UITextAlignment.Right) { xCoord -= frameSize.Width; } // subtract the frameSize so the flipped context behaves as expected yCoord -= frameSize.Height; if (centerVertical) { yCoord += (frameSize.Height / 2); } var textRect = new CGRect(xCoord, yCoord, frameSize.Width, frameSize.Height); using (CGPath path = new CGPath()) { path.AddRect(textRect); ctx.SetShadow(new CGSize(0.0f, 1.0f), 0.0f, shadowColor.CGColor); using (CTFrame frame = framesetter.GetFrame(range, path, null)) { if (flipContext) { ctx.SaveState(); ctx.TranslateCTM(0, rect.Height); ctx.ScaleCTM(1, -1); frame.Draw(ctx); ctx.RestoreState(); } else { frame.Draw(ctx); } } } } } } } } } }
public override void Draw (RectangleF rect) { // Initialize a graphics context and set the text matrix to a known value var context = UIGraphics.GetCurrentContext (); context.TextMatrix = CGAffineTransform.MakeScale (1f, -1f); var value = "This is the string that will be split across " + ColumnCount + " columns. This code brought to you by " + "ECMA 334, ECMA 335 and the Mono Team at Novell."; var framesetter = new CTFramesetter (new NSAttributedString (value)); var paths = CreateColumns (); var startIndex = 0; for (int i = 0; i < paths.Length; ++i) { var path = paths [i]; // Create a frame for this column and draw it using (var frame = framesetter.GetFrame (new NSRange (startIndex, 0), path, null)) { frame.Draw (context); var frameRange = frame.GetVisibleStringRange (); startIndex += frameRange.Length; } } }
public override void Draw (RectangleF rect) { Console.WriteLine ("# Draw: rect={{X={0}, Y={1}, Width={2}, Height={3}}}", rect.X, rect.Y, rect.Width, rect.Height); // Initialize a graphics context and set the text matrix to a known value var context = UIGraphics.GetCurrentContext (); // context.TextMatrix = CGAffineTransform.MakeIdentity (); context.TextMatrix = CGAffineTransform.MakeScale (1f, -1f); // initialize a rectangular path var path = new CGPath (); // path.AddRect (new RectangleF (10.0f, 10.0f, 200.0f, 30.0f)); path.AddRect (rect); RectangleF r; Console.WriteLine ("path.IsRect={0}; Width={1}, Height={2}", path.IsRect (out r), r.Width, r.Height); // initialize an attributed string var attrString = new NSMutableAttributedString ("We hold this truth to be self evident, that everyone is created equal."); // use a red font for the first 50 chars attrString.AddAttributes(new CTStringAttributes () { ForegroundColor = new CGColor ( CGColorSpace.CreateDeviceRGB(), new[]{1.0f, 0.0f, 0.0f, 0.8f} ), }, new NSRange (0, 50)); // Create the framesetter with the attributed string using (var framesetter = new CTFramesetter (attrString)) { NSRange fitRange; var size = framesetter.SuggestFrameSize (new NSRange (), null, new SizeF (200f, 200f), out fitRange); Console.WriteLine ("fitRange.Location={0}; fitRange.Length={1}", fitRange.Location, fitRange.Length); Console.WriteLine ("Size: Width={0}; Height={1}", size.Width, size.Height); // Create the frame and draw it into the graphics context using (var frame = framesetter.GetFrame (new NSRange (0, 70), path, null)) frame.Draw (context); context.ShowText ("hello, world!"); } }