public static void BeginImageContextWithOptions(CGSize size, bool opaque, nfloat scale) { // Create new image context ColorSpace = CGColorSpace.CreateDeviceRGB(); Context = new CGBitmapContext(null, (int)size.Width, (int)size.Height, 8, 0, ColorSpace, CGImageAlphaInfo.PremultipliedLast); // Flip context vertically var flipVertical = new CGAffineTransform(1, 0, 0, -1, 0, size.Height); Context.ConcatCTM(flipVertical); // Save previous context ImageSize = size; PreviousContext = NSGraphicsContext.CurrentContext; NSGraphicsContext.CurrentContext = NSGraphicsContext.FromCGContext(Context, true); }
public void Draw(CGContext ctx, CGColor foregroundColor, double x, double y) { bool tempForegroundSet = false; // if no color attribute is set for the whole string, // NSLayoutManager will use the default control foreground color. // To override the default color we need to apply the current CGContext stroke color // before all other attributes are set, otherwise it will remove all other foreground colors. if (foregroundColor != null && !Attributes.Any(a => a is ColorTextAttribute && a.StartIndex == 0 && a.Count == Text.Length)) { // FIXME: we need to find a better way to accomplish this without the need to reset all attributes. ResetAttributes(NSColor.FromCGColor(foregroundColor)); tempForegroundSet = true; } ctx.SaveState(); NSGraphicsContext.GlobalSaveGraphicsState(); var nsContext = NSGraphicsContext.FromCGContext(ctx, true); NSGraphicsContext.CurrentContext = nsContext; using (var TextLayout = new NSLayoutManager()) { TextLayout.AddTextContainer(TextContainer); TextStorage.AddLayoutManager(TextLayout); TextLayout.DrawBackgroundForGlyphRange(new NSRange(0, Text.Length), new CGPoint(x, y)); TextLayout.DrawGlyphsForGlyphRange(new NSRange(0, Text.Length), new CGPoint(x, y)); TextStorage.RemoveLayoutManager(TextLayout); TextLayout.RemoveTextContainer(0); } // reset foreground color change if (tempForegroundSet) { ResetAttributes(); } NSGraphicsContext.GlobalRestoreGraphicsState(); ctx.RestoreState(); }