예제 #1
0
        private static UIImage drawToken(string projectName, UIColor projectColor, UIFont font)
        {
            var stringToDraw = new NSAttributedString(
                projectName, new UIStringAttributes {
                Font = font, ForegroundColor = projectColor
            });

            var size = CalculateSize(stringToDraw, circleWidth);

            UIGraphics.BeginImageContextWithOptions(size, false, 0.0f);
            using (var context = UIGraphics.GetCurrentContext())
            {
                var tokenPath = CalculateTokenPath(size);
                context.AddPath(tokenPath.CGPath);
                context.SetFillColor(projectColor.ColorWithAlpha(0.12f).CGColor);
                context.FillPath();

                var dot = UIBezierPath.FromRoundedRect(new CGRect(
                                                           x: dotPadding + TokenMargin,
                                                           y: dotYOffset,
                                                           width: dotDiameter,
                                                           height: dotDiameter
                                                           ), dotRadius);
                context.AddPath(dot.CGPath);
                context.SetFillColor(projectColor.CGColor);
                context.FillPath();

                var textOffset = (TokenHeight - font.LineHeight) / 2;
                stringToDraw.DrawString(new CGPoint(TokenMargin + TokenPadding + circleWidth, textOffset));

                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                return(image);
            }
        }
예제 #2
0
        public override void Draw(PdfDisplayBox box, CoreGraphics.CGContext context)
        {
            // Draw original content
            base.Draw(box, context);

            using (context)
            {
                // Draw watermark underlay
                UIGraphics.PushContext(context);
                context.SaveState();

                var pageBounds = this.GetBoundsForBox(box);
                context.TranslateCTM(0.0f, pageBounds.Size.Height);
                context.ScaleCTM(1.0f, -1.0f);
                context.RotateCTM((float)(Math.PI / 4.0f));


                Console.WriteLine($"{pageBounds}");

                var attributes = new UIStringAttributes()
                {
                    ForegroundColor = UIColor.FromRGBA(255, 0, 0, 125),
                    Font            = UIFont.BoldSystemFontOfSize(84)
                };

                var text = new NSAttributedString("WATERMARK", attributes);

                text.DrawString(new CGPoint(250, 40));

                context.RestoreState();
                UIGraphics.PopContext();
            }
        }
예제 #3
0
        public ProjectTextAttachment(NSAttributedString stringToDraw, UIColor projectColor, nfloat textVerticalOffset, nfloat fontDescender)
            : base(fontDescender)
        {
            var size = CalculateSize(stringToDraw, circleWidth);

            UIGraphics.BeginImageContextWithOptions(size, false, 0.0f);
            using (var context = UIGraphics.GetCurrentContext())
            {
                var tokenPath = CalculateTokenPath(size);
                context.AddPath(tokenPath.CGPath);
                context.SetFillColor(projectColor.ColorWithAlpha(0.12f).CGColor);
                context.FillPath();

                var dot = UIBezierPath.FromRoundedRect(new CGRect(
                                                           x: dotPadding + TokenMargin,
                                                           y: dotYOffset,
                                                           width: dotDiameter,
                                                           height: dotDiameter
                                                           ), dotRadius);
                context.AddPath(dot.CGPath);
                context.SetFillColor(projectColor.CGColor);
                context.FillPath();

                stringToDraw.DrawString(new CGPoint(circleWidth + TokenMargin + TokenPadding, textVerticalOffset));

                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                Image = image;
            }
        }
예제 #4
0
        public Task <UIImage> LoadImageAsync(
            ImageSource imagesource,
            CancellationToken cancelationToken = default(CancellationToken),
            float scale = 1f)
        {
            UIImage image      = null;
            var     fontsource = imagesource as FontImageSource;

            if (fontsource != null)
            {
                var iconcolor = fontsource.Color != Color.Default ? fontsource.Color : Color.White;
                var imagesize = new SizeF((float)fontsource.Size, (float)fontsource.Size);
                var font      = UIFont.FromName(fontsource.FontFamily ?? string.Empty, (float)fontsource.Size) ??
                                UIFont.SystemFontOfSize((float)fontsource.Size);

                UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f);
                var attString    = new NSAttributedString(fontsource.Glyph, font: font, foregroundColor: iconcolor.ToUIColor());
                var ctx          = new NSStringDrawingContext();
                var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx);
                attString.DrawString(new RectangleF(
                                         imagesize.Width / 2 - boundingRect.Size.Width / 2,
                                         imagesize.Height / 2 - boundingRect.Size.Height / 2,
                                         imagesize.Width,
                                         imagesize.Height));
                image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                if (iconcolor != Color.Default)
                {
                    image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
                }
            }
            return(Task.FromResult(image));
        }
예제 #5
0
        internal UIImage RenderImage(IFontImageSource imageSource, float scale)
        {
            var font  = FontManager.GetFont(imageSource.Font);
            var color = (imageSource.Color ?? Colors.White).ToPlatform();
            var glyph = (NSString)imageSource.Glyph;

            var attString = new NSAttributedString(glyph, font, color);
            var imagesize = glyph.GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _));

            UIGraphics.BeginImageContextWithOptions(imagesize, false, scale);
            var ctx = new NSStringDrawingContext();

            var boundingRect = attString.GetBoundingRect(imagesize, 0, ctx);

            attString.DrawString(new CGRect(
                                     imagesize.Width / 2 - boundingRect.Size.Width / 2,
                                     imagesize.Height / 2 - boundingRect.Size.Height / 2,
                                     imagesize.Width,
                                     imagesize.Height));

            var image = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();

            return(image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal));
        }
예제 #6
0
        public Task <UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default, float scale = 1)
        {
            UIImage image = null;

            if (imagesource is IconImageSource iconsource && FontRegistry.HasFont(iconsource.Name, out var font))
            {
                // This will allow lookup from the Embedded Fonts
                var glyph        = font.GetGlyph(iconsource.Name);
                var cleansedname = FontExtensions.CleanseFontName(font.Alias);
                var uifont       = UIFont.FromName(cleansedname ?? string.Empty, (float)iconsource.Size) ??
                                   UIFont.SystemFontOfSize((float)iconsource.Size);
                var iconcolor = iconsource.Color.IsDefault ? _defaultColor : iconsource.Color;
                var attString = new NSAttributedString(glyph, font: uifont, foregroundColor: iconcolor.ToUIColor());
                var imagesize = ((NSString)glyph).GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _));

                UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f);
                var ctx          = new NSStringDrawingContext();
                var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx);
                attString.DrawString(new RectangleF(
                                         (imagesize.Width / 2) - (boundingRect.Size.Width / 2),
                                         (imagesize.Height / 2) - (boundingRect.Size.Height / 2),
                                         imagesize.Width,
                                         imagesize.Height));
                image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                if (image != null && iconcolor != _defaultColor)
                {
                    image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
                }
            }
            return(Task.FromResult(image));
        }
예제 #7
0
        private static UIImage drawToken(string tagName, UIColor color, UIFont font)
        {
            var stringToDraw = new NSAttributedString(
                tagName, new UIStringAttributes {
                Font = font, ForegroundColor = color
            });

            var size = CalculateSize(stringToDraw);

            UIGraphics.BeginImageContextWithOptions(size, false, 0.0f);
            using (var context = UIGraphics.GetCurrentContext())
            {
                var tokenPath = CalculateTokenPath(size);
                context.AddPath(tokenPath.CGPath);
                context.SetStrokeColor(borderColor.CGColor);
                context.StrokePath();

                var textOffset = (TokenHeight - font.LineHeight) / 2;
                stringToDraw.DrawString(new CGPoint(TokenMargin + TokenPadding, textOffset));

                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                return(image);
            }
        }
예제 #8
0
        public TokenTextAttachment(
            NSAttributedString tokenStringToDraw,
            nfloat textVerticalOffset,
            nfloat fontDescender,
            int leftMargin,
            int rightMargin)
        {
            var size = new CGSize(
                tokenStringToDraw.Size.Width + leftMargin + rightMargin + (tokenPadding * 2),
                lineHeight
                );

            UIGraphics.BeginImageContextWithOptions(size, false, 0.0f);
            using (var context = UIGraphics.GetCurrentContext())
            {
                var tokenPath = UIBezierPath.FromRoundedRect(new CGRect(
                                                                 x: leftMargin,
                                                                 y: tokenVerticallOffset,
                                                                 width: size.Width - leftMargin - rightMargin,
                                                                 height: tokenHeight
                                                                 ), tokenCornerRadius);
                context.AddPath(tokenPath.CGPath);
                context.SetStrokeColor(borderColor.CGColor);
                context.StrokePath();

                tokenStringToDraw.DrawString(new CGPoint(leftMargin + tokenPadding, textVerticalOffset));

                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                Image = image;
            }

            FontDescender = fontDescender;
        }
예제 #9
0
        public Task <UIImage> LoadImageAsync(ImageSource imagesource, CancellationToken cancelationToken = default, float scale = 1)
        {
            UIImage image = null;

            if (imagesource is IconImageSource iconsource && IconFontRegistry.Instance.TryFindIconForKey(iconsource.Name, out var icon))
            {
                var iconcolor = iconsource.Color.IsDefault ? _defaultColor : iconsource.Color;
                var imagesize = new SizeF((float)iconsource.Size, (float)iconsource.Size);
                var font      = UIFont.FromName(icon.FontFamily ?? string.Empty, (float)iconsource.Size) ??
                                UIFont.SystemFontOfSize((float)iconsource.Size);

                UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f);
                var attString    = new NSAttributedString(icon.Glyph, font: font, foregroundColor: iconcolor.ToUIColor());
                var ctx          = new NSStringDrawingContext();
                var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx);
                attString.DrawString(new RectangleF(
                                         (imagesize.Width / 2) - (boundingRect.Size.Width / 2),
                                         (imagesize.Height / 2) - (boundingRect.Size.Height / 2),
                                         imagesize.Width,
                                         imagesize.Height));
                image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                if (iconcolor != _defaultColor)
                {
                    image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
                }
            }
            return(Task.FromResult(image));
        }
예제 #10
0
        public Task <UIImage> LoadImageAsync(
            ImageSource imagesource,
            CancellationToken cancelationToken = default(CancellationToken),
            float scale = 1f)
        {
            UIImage image      = null;
            var     fontsource = imagesource as FontImageSource;

            if (fontsource != null)
            {
                // This will allow lookup from the Embedded Fonts
                var font      = Font.OfSize(fontsource.FontFamily, fontsource.Size).ToUIFont();
                var iconcolor = fontsource.Color ?? _defaultColor;
                var attString = new NSAttributedString(fontsource.Glyph, font: font, foregroundColor: iconcolor.ToUIColor());
                var imagesize = ((NSString)fontsource.Glyph).GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _));

                UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f);
                var ctx          = new NSStringDrawingContext();
                var boundingRect = attString.GetBoundingRect(imagesize, (NSStringDrawingOptions)0, ctx);
                attString.DrawString(new RectangleF(
                                         imagesize.Width / 2 - boundingRect.Size.Width / 2,
                                         imagesize.Height / 2 - boundingRect.Size.Height / 2,
                                         imagesize.Width,
                                         imagesize.Height));
                image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();

                if (image != null && iconcolor != _defaultColor)
                {
                    image = image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal);
                }
            }
            return(Task.FromResult(image));
        }
예제 #11
0
파일: TextBlock.iOS.cs 프로젝트: zzyzy/uno
 public override void Draw(CGRect rect)
 {
     _drawRect = GetDrawRect(rect);
     if (UseLayoutManager)
     {
         _layoutManager?.DrawGlyphs(new NSRange(0, (nint)_layoutManager.NumberOfGlyphs), _drawRect.Location);
     }
     else
     {
         _attributedString?.DrawString(_drawRect, NSStringDrawingOptions.UsesLineFragmentOrigin, null);
     }
 }
예제 #12
0
        private void DrawText(string t, nfloat x, nfloat y, nfloat fontSize, CGColor color)
        {
            var attributedString = new NSAttributedString(t, new CTStringAttributes
            {
                ForegroundColorFromContext = true,
                ForegroundColor            = color,
                StrokeColor = color,
                Font        = new CTFont("SFUIDisplay-Regular", fontSize)
            });

            attributedString.DrawString(new CGPoint(x, y));
        }
예제 #13
0
파일: DrawText.cs 프로젝트: thanhbv21/scann
        public static UIImage DrawTextInImage1(UIImage uiImage, NSString text, NSString text1, CGPoint point)
        {
            nfloat fWidth  = uiImage.Size.Width;
            nfloat fHeight = uiImage.Size.Height;

            nfloat afHeight   = uiImage.Size.Height / 5;
            UIFont font       = UIFont.BoldSystemFontOfSize(50);
            UIFont authorfont = UIFont.SystemFontOfSize(45);
            var    imagesize  = new CGSize(fWidth, fHeight + afHeight);

            UIGraphics.BeginImageContext(imagesize);

            UIImage background = new UIImage();

            background.Draw(new CGRect(0, 0, fWidth, fHeight + afHeight));
            uiImage.Draw(new CGRect(0, 0, fWidth, fHeight));

            var style = new NSMutableParagraphStyle();

            style.Alignment = UITextAlignment.Center;
            var att = new NSAttributedString(text,
                                             font: font,
                                             paragraphStyle: style,
                                             foregroundColor: UIColor.White
                                             );

            var author = new NSAttributedString(text1,
                                                font: authorfont,
                                                paragraphStyle: style,
                                                foregroundColor: UIColor.Black
                                                );
            CGRect stringrect = att.GetBoundingRect(new CGSize(fWidth - 100, fHeight + afHeight), NSStringDrawingOptions.UsesLineFragmentOrigin, null);

            System.Diagnostics.Debug.WriteLine("width:" + stringrect.Size.Width + " height:" + stringrect.Size.Height);
            nfloat yOffset    = (fHeight - stringrect.Size.Height) / 2;
            nfloat heightsize = stringrect.Size.Height + yOffset;

            System.Diagnostics.Debug.WriteLine("yOffset + height:" + heightsize);
            CGRect rect = new CGRect(point.X + 50, yOffset, fWidth - 100, fHeight + afHeight);

            att.DrawString(rect.Integral());

            CGRect rect1 = new CGRect(point.X, fHeight + (afHeight - authorfont.LineHeight) / 2, fWidth, 50);

            author.DrawString(rect1.Integral());

            UIImage resultImage = UIGraphics.GetImageFromCurrentImageContext();

            UIGraphics.EndImageContext();
            return(resultImage);
        }
예제 #14
0
        public override void DrawRect(CGRect rect)
        {
            _drawRect = GetDrawRect(rect);
            if (UseLayoutManager)
            {
                // DrawGlyphsForGlyphRange is the method we want to use here since DrawBackgroundForGlyphRange is intended for something different.
                // While DrawBackgroundForGlyphRange will draw the background mark for specified Glyphs DrawGlyphsForGlyphRange will draw the actual Glyphs.

                // Note: This part of the code is called only under very specific situations. For most of the scenarios DrawString is used to draw the text.
                _layoutManager?.DrawGlyphsForGlyphRange(new NSRange(0, (nint)_layoutManager.NumberOfGlyphs), _drawRect.Location);
            }
            else
            {
                _attributedString?.DrawString(_drawRect, NSStringDrawingOptions.UsesLineFragmentOrigin);
            }
        }
        public static UIImage ToUIImage(this IIcon icon, nfloat size)
        {
            var attributedString = new NSAttributedString($"{icon.Character}", new CTStringAttributes
            {
                Font = new CTFont(Iconize.FindModuleOf(icon).FontName, size),
                ForegroundColorFromContext = true
            });

            var boundSize = attributedString.GetBoundingRect(new CGSize(10000, 10000), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size;

            UIGraphics.BeginImageContextWithOptions(boundSize, false, 0f);
            attributedString.DrawString(new CGRect(0, 0, boundSize.Width, boundSize.Height));
            var image = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();

            return image;
        }
예제 #16
0
        public override void DrawRect(CGRect dirtyRect)
        {
            var window            = ((AppStoreWindow)Window);
            var drawsAsMainWindow = window.DrawsAsMainWindow();

            // Start by filling the title bar area with black in fullscreen mode to match native apps
            // Custom title bar drawing blocks can simply override this by not applying the clipping path
            if (window.IsFullScreen())
            {
                NSColor.Black.SetFill();
                NSBezierPath.FromRect(Bounds).Fill();
            }

            CGPath clippingPath;
            var    drawingRect = Bounds;

            if (window.TitleBarDrawingCallbackAction != null)
            {
                clippingPath = DrawingHelper.CreateClippingPath(drawingRect, CORNER_CLIP_RADIUS);
                window.TitleBarDrawingCallbackAction(drawsAsMainWindow, drawingRect, clippingPath);
            }
            else
            {
                // There's a thin whitish line between the darker gray window border line
                // and the gray noise textured gradient; preserve that when drawing a native title bar
                var clippingRect = drawingRect;
                clippingRect.Height -= 1;
                clippingPath         = DrawingHelper.CreateClippingPath(clippingRect, CORNER_CLIP_RADIUS);

                DrawWindowBackgroundGradient(drawingRect, clippingPath);
            }

            if (window.ShowsTitle && ((window.StyleMask & NSWindowStyle.FullScreenWindow) == 0 || window.ShowsTitleInFullscreen))
            {
                NSDictionary dictionary;
                var          titleTextRect = GetTitleFrame(out dictionary, window);

                if (window.VerticallyCenterTitle)
                {
                    titleTextRect.Y = (float)Math.Floor(drawingRect.GetMidY() - titleTextRect.Height / 2f + 1);
                }

                var title = new NSAttributedString(window.Title, dictionary);
                title.DrawString(titleTextRect);
            }
        }
예제 #17
0
        public static UIImage ConvertFontIconToUIImage(string fontFamily, double fontSize, UIColor iconcolor, string glyph)
        {
            UIImage image        = null;
            var     cleansedname = CleanseFontName(fontFamily);
            var     font         = UIFont.FromName(cleansedname ?? string.Empty, (float)fontSize) ?? UIFont.SystemFontOfSize((float)fontSize);
            var     attString    = new NSAttributedString(glyph, font: font, foregroundColor: iconcolor);
            var     imagesize    = ((NSString)glyph).GetSizeUsingAttributes(attString.GetUIKitAttributes(0, out _));

            UIGraphics.BeginImageContextWithOptions(imagesize, false, 0f);
            var ctx          = new NSStringDrawingContext();
            var boundingRect = attString.GetBoundingRect(imagesize, 0, ctx);

            attString.DrawString(new DrawRect((float)(imagesize.Width / 2 - boundingRect.Size.Width / 2), (float)(imagesize.Height / 2 - boundingRect.Size.Height / 2), (float)imagesize.Width, (float)imagesize.Height));
            image = UIGraphics.GetImageFromCurrentImageContext();
            UIGraphics.EndImageContext();
            return(image);
        }
예제 #18
0
 protected virtual void DrawCenteredText(CGContext context, String text, float cx, float cy)
 {
     CGPoint cgp = new CGPoint(cx, cy);
     UIFont uif = UIFont.FromName("Arial", 24);
     NSParagraphStyle nsps = new NSParagraphStyle()
     {
         Alignment = UITextAlignment.Center
     };
     //NSAttributedString nsas = new NSAttributedString(str: text,
     //                                                 font: uif,
     //                                                 foregroundColor: UIColor.Red,
     //                                                 paragraphStyle: nsps);
     NSAttributedString nsas = new NSAttributedString(str: text,
                                                      font: uif,
                                                      foregroundColor: UIColor.Red);
     nsas.DrawString(cgp);
 }
예제 #19
0
        public TokenTextAttachment(
            NSAttributedString projectStringToDraw,
            nfloat textVerticalOffset,
            UIColor projectColor,
            nfloat fontDescender,
            int leftMargin,
            int rightMargin)
        {
            const int circleWidth = dotDiameter + dotPadding;
            var       totalWidth  = projectStringToDraw.Size.Width + circleWidth + leftMargin + rightMargin + (tokenPadding * 2);
            var       size        = new CGSize(totalWidth, lineHeight);

            UIGraphics.BeginImageContextWithOptions(size, false, 0.0f);
            using (var context = UIGraphics.GetCurrentContext())
            {
                var tokenPath = UIBezierPath.FromRoundedRect(new CGRect(
                                                                 x: leftMargin,
                                                                 y: tokenVerticallOffset,
                                                                 width: totalWidth - leftMargin - rightMargin,
                                                                 height: tokenHeight
                                                                 ), tokenCornerRadius);
                context.AddPath(tokenPath.CGPath);
                context.SetFillColor(projectColor.ColorWithAlpha(0.12f).CGColor);
                context.FillPath();

                var dot = UIBezierPath.FromRoundedRect(new CGRect(
                                                           x: dotPadding + leftMargin,
                                                           y: dotYOffset,
                                                           width: dotDiameter,
                                                           height: dotDiameter
                                                           ), dotRadius);
                context.AddPath(dot.CGPath);
                context.SetFillColor(projectColor.CGColor);
                context.FillPath();

                projectStringToDraw.DrawString(new CGPoint(circleWidth + leftMargin + tokenPadding, textVerticalOffset));

                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                Image = image;
            }

            FontDescender = fontDescender;
        }
예제 #20
0
        /// <summary>
        /// To the UI image.
        /// </summary>
        /// <param name="iconChar">The character value for the desired icon.</param>
        /// <param name="size">The size.</param>
        /// <returns></returns>
        private UIImage GetUIImage(char iconChar, nfloat size)
        {
            var attributedString = new NSAttributedString($"{iconChar}", new CTStringAttributes
            {
                Font = new CTFont(FontAwesomeRegular.FontName, size),
                ForegroundColorFromContext = true
            });

            var boundSize = attributedString.GetBoundingRect(new CGSize(10000f, 10000f), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size;

            UIGraphics.BeginImageContextWithOptions(boundSize, false, 0f);
            attributedString.DrawString(new CGRect(0f, 0f, boundSize.Width, boundSize.Height));
            using (var image = UIGraphics.GetImageFromCurrentImageContext())
            {
                UIGraphics.EndImageContext();

                return(image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate));
            }
        }
        /// <summary>
        /// To the UI image.
        /// </summary>
        /// <param name="icon">The icon.</param>
        /// <param name="size">The size.</param>
        /// <returns></returns>
        public static UIImage ToUIImage(this IIcon icon, nfloat size)
        {
            var attributedString = new NSAttributedString($"{icon.Character}", new CTStringAttributes
            {
                Font = new CTFont(IconFonts.FindModuleOf(icon).FontName, size),
                ForegroundColorFromContext = true
            });

            var boundSize = attributedString.GetBoundingRect(new CGSize(10000f, 10000f), NSStringDrawingOptions.UsesLineFragmentOrigin, null).Size;

            UIGraphics.BeginImageContextWithOptions(boundSize, false, 0f);
            attributedString.DrawString(new CGRect(0f, 0f, boundSize.Width, boundSize.Height));
            using (var image = UIGraphics.GetImageFromCurrentImageContext())
            {
                UIGraphics.EndImageContext();

                return(image.ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate));
            }
        }
예제 #22
0
        public TagTextAttachment(NSAttributedString stringToDraw, nfloat textVerticalOffset, nfloat fontDescender)
            : base(fontDescender)
        {
            var size = CalculateSize(stringToDraw);

            UIGraphics.BeginImageContextWithOptions(size, false, 0.0f);
            using (var context = UIGraphics.GetCurrentContext())
            {
                var tokenPath = CalculateTokenPath(size);
                context.AddPath(tokenPath.CGPath);
                context.SetStrokeColor(borderColor.CGColor);
                context.StrokePath();

                stringToDraw.DrawString(new CGPoint(TokenMargin + TokenPadding, textVerticalOffset));

                var image = UIGraphics.GetImageFromCurrentImageContext();
                UIGraphics.EndImageContext();
                Image = image;
            }
        }
예제 #23
0
        public void DrawText(string text)
        {
            Ensure();

            var gc = NSGraphicsContext.FromGraphicsPort(context, false);

            gc.SaveGraphicsState();
            NSGraphicsContext.CurrentContext = gc;

            var str  = new NSAttributedString(text, foregroundColor: Color, font: Font);
            var size = str.Size;

            var box = Bounds;

            switch (HAlign)
            {
            case NSTextAlignment.Right:
                box.X += box.Width - size.Width;
                break;

            case NSTextAlignment.Center:
                box.X += (box.Width - size.Width) / 2;
                break;
            }

            switch (VAlign)
            {
            case NSTextAlignment.Left:
                box.Y += box.Height - size.Height;
                break;

            case NSTextAlignment.Center:
                box.Y += (box.Height - size.Height) / 2;
                break;
            }

            str.DrawString(box.Location);

            NSGraphicsContext.GlobalRestoreGraphicsState();
        }
예제 #24
0
 public override void DrawWithFrame(CGRect cellFrame, NSView inView)
 {
     if (NSGraphicsContext.IsCurrentContextDrawingToScreen)
     {
         base.DrawWithFrame(cellFrame, inView);
     }
     else
     {
         DrawTitle(AttributedTitle, TitleRectForBounds(cellFrame), inView);
         var state      = State;
         var text       = state == NSCellStateValue.On ? "⦿" : state == NSCellStateValue.Mixed ? "⊖" : "○";
         var font       = NSFont.SystemFontOfSize(NSFont.SystemFontSizeForControlSize(ControlSize));
         var attributes = NSDictionary.FromObjectAndKey(font, NSStringAttributeKey.Font);
         var str        = new NSAttributedString(text, attributes);
         var frame      = cellFrame;
         var size       = str.Size;
         var offset     = (nfloat)Math.Max(0, (frame.Height - size.Height) / 2);
         frame.Y      += offset;
         frame.Height -= offset;
         str.DrawString(frame);
     }
 }
        public override void Draw(CGRect rect)
        {
            W = (float)Bounds.Width / 2;
            H = (float)Bounds.Height * 0.70f;
            var context = UIGraphics.GetCurrentContext();

            var attributes = new UIStringAttributes
            {
                Font            = UIFont.SystemFontOfSize(40),
                ForegroundColor = UIColor.White
            };

            var text = new NSAttributedString((SliderPosition / MaxSize).ToString("p1"), attributes);
            var size = text.Size;

            var bezierPath = new UIBezierPath();


            switch (DrawableFigure)
            {
            case (int)Figures.rectangle:     //rectangle
            {
                text.DrawString(new CGPoint(Bounds.GetMidX() - size.Width / 2, Bounds.GetMidY() + H / 2 - (H / MaxSize * SliderPosition) - size.Height));
                UIColor.Red.SetFill();
                UIColor.Blue.SetStroke();
                bezierPath.MoveTo(new CGPoint(Bounds.GetMidX() + W / 2, Bounds.GetMidY() + H / 2));
                bezierPath.AddLineTo(new CGPoint(Bounds.GetMidX() - W / 2, Bounds.GetMidY() + H / 2));
                bezierPath.AddLineTo(new CGPoint(Bounds.GetMidX() - W / 2, Bounds.GetMidY() + H / 2 - (H / MaxSize * SliderPosition)));
                bezierPath.AddLineTo(new CGPoint(Bounds.GetMidX() + W / 2, Bounds.GetMidY() + H / 2 - (H / MaxSize * SliderPosition)));
                bezierPath.ClosePath();
                bezierPath.Fill();
                break;
            }

            case (int)Figures.manyRectangle:      //many rectangles
            {
                var sizeOneRectangle      = H / 5;
                var sizeBorderRectangle   = H / MaxSize * SliderPosition;
                var countRectangle        = sizeBorderRectangle / sizeOneRectangle;
                var spaceBetweenRectangle = sizeOneRectangle / 5;
                text.DrawString(new CGPoint(Bounds.GetMidX() - size.Width / 2, Bounds.GetMidY() + H / 2 - sizeOneRectangle * Math.Ceiling(countRectangle) - size.Height));

                for (int i = 0; i < countRectangle; i++)
                {
                    UIColor.Red.SetFill();
                    UIColor.Blue.SetStroke();
                    var startPositionYRectangle = Bounds.GetMidY() + H / 2 - sizeOneRectangle * i;

                    bezierPath.MoveTo(new CGPoint(Bounds.GetMidX() + W / 2, startPositionYRectangle));
                    bezierPath.AddLineTo(new CGPoint(Bounds.GetMidX() - W / 2, startPositionYRectangle));
                    bezierPath.AddLineTo(new CGPoint(Bounds.GetMidX() - W / 2, startPositionYRectangle - sizeOneRectangle + spaceBetweenRectangle));
                    bezierPath.AddLineTo(new CGPoint(Bounds.GetMidX() + W / 2, startPositionYRectangle - sizeOneRectangle + spaceBetweenRectangle));
                    bezierPath.ClosePath();
                    bezierPath.Fill();
                }
                break;
            }

            case (int)Figures.circle:     //circle
            {
                text.DrawString(new CGPoint(Bounds.GetMidX() - size.Width / 2, Bounds.GetMidY() - size.Height / 2));
                UIColor.Red.SetStroke();
                var startDegree = Radiant(270);
                var endDegree   = Radiant(SliderPosition);

                bezierPath.AddArc(new CGPoint(Bounds.GetMidX(), Bounds.GetMidY()), (nfloat)Math.Min(Bounds.Width, Bounds.Height) * 0.45f,
                                  startDegree,
                                  startDegree + endDegree, true);
                break;
            }

            default: break;
            }

            bezierPath.LineWidth = 5;
            bezierPath.Stroke();
        }
예제 #26
0
        private VehicleImageContext GenerateMarkerImageWithText(string vehicleName)
        {
            NSString           markerText = new NSString(vehicleName);
            UIStringAttributes attributes = new UIStringAttributes {
                Font = UIFont.FromName("Arial", 16), ForegroundColor = UIColor.White
            };
            CGSize sizeOfMarkerText = markerText.GetSizeUsingAttributes(attributes);

            NSAttributedString markerString = new NSAttributedString(vehicleName, attributes);

            // Calculate element sizes depending on text and text attributes like font and font size
            float labelHeight  = (float)Math.Ceiling(sizeOfMarkerText.Height * 2.0);
            float labelWidth   = (float)Math.Ceiling(sizeOfMarkerText.Width);
            float labelEndSize = labelHeight;
            float gpsPointSize = 10.0f;
            float distanceBetweenLabelAndPoint = 10;

            CGSize imageSize = new CGSize(labelWidth + (labelEndSize), labelHeight + distanceBetweenLabelAndPoint + gpsPointSize);

            UIGraphicsImageRenderer renderer = new UIGraphicsImageRenderer(imageSize);
            UIImage image = renderer.CreateImage((context) =>
            {
                // Color Declarations
                UIColor blueZodiacColor = new UIColor(15.0f / 255f, 42.0f / 255f, 72.0f / 255f, 1.0f);

                // Draw label rectangle
                nfloat rectX               = labelEndSize / 2.0f;
                nfloat rectY               = 0;
                nfloat rectWidth           = labelWidth;
                nfloat rectHeight          = labelHeight;
                CGRect rectangleSize       = new CGRect(rectX, rectY, rectWidth, rectHeight);
                UIBezierPath rectanglePath = UIBezierPath.FromRect(rectangleSize);
                blueZodiacColor.SetFill();
                rectanglePath.Fill();

                // Draw text
                nfloat textX      = rectangleSize.Location.X;
                nfloat textY      = rectangleSize.Location.Y + (rectangleSize.Size.Height / 4.0f);
                nfloat textWidth  = labelWidth;
                nfloat textHeight = labelHeight;
                markerString.DrawString(new CGRect(textX, textY, textWidth, textHeight));

                // Draw label end left
                nfloat endLeftX             = 0;
                nfloat endLeftY             = 0;
                CGRect endcupLeftRect       = new CGRect(endLeftX, endLeftY, labelEndSize, labelEndSize);
                UIBezierPath endcupLeftPath = new UIBezierPath();
                endcupLeftPath.AddArc(new CGPoint(endcupLeftRect.GetMidX(), endcupLeftRect.GetMidY()), endcupLeftRect.Size.Width / 2, (nfloat)(90.0d * Math.PI / 180.0d), (nfloat)(-90.0d * Math.PI / 180.0d), true);
                endcupLeftPath.AddLineTo(new CGPoint(endcupLeftRect.GetMidX(), endcupLeftRect.GetMidY()));
                endcupLeftPath.ClosePath();

                blueZodiacColor.SetFill();
                endcupLeftPath.Fill();

                // Draw label end right
                nfloat endRightX             = rectangleSize.Size.Width;
                nfloat endRightY             = 0;
                CGRect endcupRightRect       = new CGRect(endRightX, endRightY, labelEndSize, labelEndSize);
                UIBezierPath endcupRightPath = new UIBezierPath();
                endcupRightPath.AddArc(new CGPoint(endcupRightRect.GetMidX(), endcupRightRect.GetMidY()), endcupRightRect.Size.Width / 2, (nfloat)(270d * Math.PI / 180d), (nfloat)(90d * Math.PI / 180d), true);
                endcupRightPath.AddLineTo(new CGPoint(endcupRightRect.GetMidX(), endcupRightRect.GetMidY()));
                endcupRightPath.ClosePath();

                blueZodiacColor.SetFill();
                endcupRightPath.Fill();

                // Draw GPS point
                nfloat pointX             = (nfloat)((imageSize.Width / 2.0) - (gpsPointSize / 2.0));
                nfloat pointY             = labelHeight + distanceBetweenLabelAndPoint;
                UIBezierPath gpsPointPath = UIBezierPath.FromOval(new CGRect(pointX, pointY, gpsPointSize, gpsPointSize));
                blueZodiacColor.SetFill();
                gpsPointPath.Fill();
            });

            // Create vehicle image context and set image
            VehicleImageContext vehicleImageContext = new VehicleImageContext();

            vehicleImageContext.image = image;
            // Calculate anchor offset to place the image correctly on the map
            vehicleImageContext.anchorOffset = new CGPoint(0.0, -((imageSize.Height / 2.0) - (gpsPointSize / 2.0)));

            return(vehicleImageContext);
        }
예제 #27
0
		public static SCNNode SCBoxNode (string title, CGRect frame, NSColor color, float cornerRadius, bool centered)
		{
			NSMutableDictionary titleAttributes = null;
			NSMutableDictionary centeredTitleAttributes = null;

			// create and extrude a bezier path to build the box
			var path = NSBezierPath.FromRoundedRect (frame, cornerRadius, cornerRadius);
			path.Flatness = 0.05f;

			var shape = SCNShape.Create (path, 20);
			shape.ChamferRadius = 0.0f;

			var node = SCNNode.Create ();
			node.Geometry = shape;

			// create an image and fill with the color and text
			var textureSize = new CGSize ();
			textureSize.Width = NMath.Ceiling (frame.Size.Width * 1.5f);
			textureSize.Height = NMath.Ceiling (frame.Size.Height * 1.5f);

			var texture = new NSImage (textureSize);
			texture.LockFocus ();

			var drawFrame = new CGRect (0, 0, textureSize.Width, textureSize.Height);

			nfloat hue, saturation, brightness, alpha;

			(color.UsingColorSpace (NSColorSpace.DeviceRGBColorSpace)).GetHsba (out hue, out saturation, out brightness, out alpha);
			var lightColor = NSColor.FromDeviceHsba (hue, saturation - 0.2f, brightness + 0.3f, alpha);
			lightColor.Set ();

			NSGraphics.RectFill (drawFrame);

			NSBezierPath fillpath = null;

			if (cornerRadius == 0 && centered == false) {
				//special case for the "labs" slide
				drawFrame.Offset (0, -2);
				fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius);
			} else {
				drawFrame.Inflate (-3, -3);
				fillpath = NSBezierPath.FromRoundedRect (drawFrame, cornerRadius, cornerRadius);
			}

			color.Set ();
			fillpath.Fill ();

			// draw the title if any
			if (title != null) {
				if (titleAttributes == null) {
					var paraphStyle = new NSMutableParagraphStyle ();
					paraphStyle.LineBreakMode = NSLineBreakMode.ByWordWrapping;
					paraphStyle.Alignment = NSTextAlignment.Center;
					paraphStyle.MinimumLineHeight = 38;
					paraphStyle.MaximumLineHeight = 38;

					var font = NSFont.FromFontName ("Myriad Set Semibold", 34) != null ? NSFont.FromFontName ("Myriad Set Semibold", 34) : NSFont.FromFontName ("Avenir Medium", 34);

					var shadow = new NSShadow ();
					shadow.ShadowOffset = new CGSize (0, -2);
					shadow.ShadowBlurRadius = 4;
					shadow.ShadowColor = NSColor.FromDeviceWhite (0.0f, 0.5f);

					titleAttributes = new NSMutableDictionary ();
					titleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName);
					titleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName);
					titleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName);
					titleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName);

					var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy ();
					centeredParaphStyle.Alignment = NSTextAlignment.Center;

					centeredTitleAttributes = new NSMutableDictionary ();
					centeredTitleAttributes.SetValueForKey (font, NSAttributedString.FontAttributeName);
					centeredTitleAttributes.SetValueForKey (NSColor.White, NSAttributedString.ForegroundColorAttributeName);
					centeredTitleAttributes.SetValueForKey (shadow, NSAttributedString.ShadowAttributeName);
					centeredTitleAttributes.SetValueForKey (paraphStyle, NSAttributedString.ParagraphStyleAttributeName);
				}

				var attrString = new NSAttributedString (title, centered ? centeredTitleAttributes : titleAttributes);
				var textSize = attrString.Size;

				//check if we need two lines to draw the text
				var twoLines = title.Contains ("\n");
				if (!twoLines)
					twoLines = textSize.Width > frame.Size.Width && title.Contains (" ");

				//if so, we need to adjust the size to center vertically
				if (twoLines)
					textSize.Height += 38;

				if (!centered)
					drawFrame.Inflate (-15, 0);

				//center vertically
				var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f;
				var drawFrameHeight = drawFrame.Size.Height;
				drawFrame.Size = new CGSize (drawFrame.Size.Width, drawFrame.Size.Height - dy);
				attrString.DrawString (drawFrame);
			}

			texture.UnlockFocus ();

			//set the created image as the diffuse texture of our 3D box
			var front = SCNMaterial.Create ();
			front.Diffuse.Contents = texture;
			front.LocksAmbientWithDiffuse = true;

			//use a lighter color for the chamfer and sides
			var sides = SCNMaterial.Create ();
			sides.Diffuse.Contents = lightColor;
			node.Geometry.Materials = new SCNMaterial[] {
				front,
				sides,
				sides,
				sides,
				sides
			};

			return node;
		}
예제 #28
0
 public static void DrawInRect(this NSAttributedString text, CGRect rect) =>
 text.DrawString(rect);
예제 #29
0
        private void DrawRectangle(CGContext g, PinboardData.RectangleInfo rectInfo)
        {
            g.SetFillColor(rectInfo.Color);
            g.FillRect(rectInfo.Rectangle);

            float pw = 0.5f;
            CGColor rectBorderColor = new CGColor(0f, rectInfo.Color.Alpha);

            g.SetLineWidth(pw);
            g.SetStrokeColor(rectBorderColor);
            g.SetFillColor(rectInfo.Color);
            g.SetLineJoin(CGLineJoin.Miter);
            g.BeginPath();
            g.StrokeRect(rectInfo.Rectangle);

            int margin = 5;
            // TODO: Make the font configurable
            NSFont font = NSFont.FromFontName("Helvetica", 12f);
            NSObject[] objects = new NSObject[] { font, (NSNumber)0 };
            NSObject[] keys = new NSObject[] { NSAttributedString.FontAttributeName, NSAttributedString.LigatureAttributeName };
            NSDictionary attributes = NSDictionary.FromObjectsAndKeys(objects, keys);
            NSAttributedString attrString = new NSAttributedString(rectInfo.Name, attributes);

            attrString.DrawString(new RectangleF(rectInfo.X + margin, rectInfo.Y + margin, rectInfo.Width - 2 * margin, rectInfo.Height - 2 * margin));
        }
예제 #30
0
        internal CCTexture2D CreateTextSprite(string text, CCFontDefinition textDefinition)
        {
            if (string.IsNullOrEmpty(text))
            {
                return(new CCTexture2D());
            }

            int imageWidth;
            int imageHeight;
            var textDef = textDefinition;
            var contentScaleFactorWidth  = CCLabel.DefaultTexelToContentSizeRatios.Width;
            var contentScaleFactorHeight = CCLabel.DefaultTexelToContentSizeRatios.Height;

            textDef.FontSize          *= contentScaleFactorWidth;
            textDef.Dimensions.Width  *= contentScaleFactorWidth;
            textDef.Dimensions.Height *= contentScaleFactorHeight;

            bool hasPremultipliedAlpha;

            // font
            UIFont font = null;

            var ext = System.IO.Path.GetExtension(textDef.FontName);

            if (!String.IsNullOrEmpty(ext) && ext.ToLower() == ".ttf")
            {
                try
                {
                    textDef.FontName = LoadFontFile(textDef.FontName);
                    font             = UIFont.FromName(textDef.FontName, textDef.FontSize);
                }
                catch (Exception exc)
                {
                    CCLog.Log(".ttf {0} file not found or can not be loaded.", textDef.FontName);
                }
            }
            else
            {
                // font
                font = UIFont.FromName(textDef.FontName, textDef.FontSize);
                //NSFontManager.SharedFontManager.FontWithFamily(textDef.FontName, NSFontTraitMask.Unbold | NSFontTraitMask.Unitalic, 0, textDef.FontSize);
            }

            if (font == null)
            {
                font = UIFont.FromName("Arial", textDef.FontSize);
                CCLog.Log("{0} not found.  Defaulting to Arial.", textDef.FontName);
            }

            // color
            var foregroundColor = UIColor.White;

            // alignment
            var horizontalAlignment = textDef.Alignment;
            var verticleAlignement  = textDef.LineAlignment;

            var textAlign = (CCTextAlignment.Right == horizontalAlignment) ? UITextAlignment.Right
                : (CCTextAlignment.Center == horizontalAlignment) ? UITextAlignment.Center
                : UITextAlignment.Left;

            // LineBreak
            var lineBreak = (CCLabelLineBreak.Character == textDef.LineBreak) ? UILineBreakMode.CharacterWrap
                : (CCLabelLineBreak.Word == textDef.LineBreak) ? UILineBreakMode.WordWrap
                : UILineBreakMode.Clip;

            var nsparagraphStyle = (NSMutableParagraphStyle)NSParagraphStyle.Default.MutableCopy();

            nsparagraphStyle.LineBreakMode = lineBreak;
            nsparagraphStyle.Alignment     = textAlign;

            // Create a new attributed string definition
            var nsAttributes = new UIStringAttributes();

            // Font attribute
            nsAttributes.Font            = font;
            nsAttributes.ForegroundColor = foregroundColor;
            nsAttributes.ParagraphStyle  = nsparagraphStyle;

            var stringWithAttributes = new NSAttributedString(text, nsAttributes);

            var realDimensions = stringWithAttributes.Size;

            // Mac crashes if the width or height is 0
            if (realDimensions == SizeF.Empty)
            {
                throw new ArgumentOutOfRangeException("Native string:", "Dimensions of native NSAttributedString can not be 0,0");
            }

            var dimensions = new CGSize(textDef.Dimensions.Width, textDef.Dimensions.Height);

            var layoutAvailable = true;

            if (dimensions.Width <= 0)
            {
                dimensions.Width = 8388608;
                layoutAvailable  = false;
            }

            if (dimensions.Height <= 0)
            {
                dimensions.Height = 8388608;
                layoutAvailable   = false;
            }


            var boundingRect = stringWithAttributes.GetBoundingRect(new CGSize((int)dimensions.Width, (int)dimensions.Height),
                                                                    NSStringDrawingOptions.UsesLineFragmentOrigin, null);

            if (!layoutAvailable)
            {
                if (dimensions.Width == 8388608)
                {
                    dimensions.Width = boundingRect.Width;
                }
                if (dimensions.Height == 8388608)
                {
                    dimensions.Height = boundingRect.Height;
                }
            }

            imageWidth  = (int)dimensions.Width;
            imageHeight = (int)dimensions.Height;

            // Alignment
            var xOffset = (nfloat)0.0f;

            switch (textAlign)
            {
            case UITextAlignment.Left:
                xOffset = 0;
                break;

            case UITextAlignment.Center:
                xOffset = (dimensions.Width - boundingRect.Width) / 2.0f;
                break;

            case UITextAlignment.Right: xOffset = dimensions.Width - boundingRect.Width; break;

            default: break;
            }

            // Line alignment
            var yOffset = (CCVerticalTextAlignment.Bottom == verticleAlignement ||
                           boundingRect.Height >= dimensions.Height) ? (dimensions.Height - boundingRect.Height) // align to bottom
                : (CCVerticalTextAlignment.Top == verticleAlignement) ? 0                                        // align to top
                : (imageHeight - boundingRect.Height) / 2.0f;                                                    // align to center

            //Find the rect that the string will draw into inside the dimensions
            var drawRect = new CGRect(xOffset
                                      , yOffset
                                      , boundingRect.Width
                                      , boundingRect.Height);


            UIImage   image   = null;
            CGContext context = null;

            try
            {
                UIGraphics.BeginImageContext(new CGSize(imageWidth, imageHeight));
                context = UIGraphics.GetCurrentContext();

                //Set antialias or not
                context.SetShouldAntialias(textDef.isShouldAntialias);

                stringWithAttributes.DrawString(drawRect);

                image = UIGraphics.GetImageFromCurrentImageContext();

                UIGraphics.EndImageContext();

                // We will use Texture2D from stream here instead of CCTexture2D stream.
                var tex = Texture2D.FromStream(CCDrawManager.SharedDrawManager.XnaGraphicsDevice, image);

                // Debugging purposes
                //            var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
                //            var fileName = Path.Combine(path, "Label3.png");
                //            using (var stream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
                //            {
                //                tex.SaveAsPng(stream, imageWidth, imageHeight);
                //            }

                // Create our texture of the label string.
                var texture = new CCTexture2D(tex);

                return(texture);
            }
            catch (Exception exc)
            {
                CCLog.Log("CCLabel: Error creating native label:{0}\n{1}", exc.Message, exc.StackTrace);
            }
            finally
            {
                // clean up the resources
                if (image != null)
                {
                    image.Dispose();
                    image = null;
                }
                if (context != null)
                {
                    context.Dispose();
                    context = null;
                }
                if (stringWithAttributes != null)
                {
                    stringWithAttributes.Dispose();
                    stringWithAttributes = null;
                }
            }
            return(new CCTexture2D());
        }
예제 #31
0
        public static SCNNode SCBoxNode(string title, CGRect frame, NSColor color, float cornerRadius, bool centered)
        {
            NSMutableDictionary titleAttributes         = null;
            NSMutableDictionary centeredTitleAttributes = null;

            // create and extrude a bezier path to build the box
            var path = NSBezierPath.FromRoundedRect(frame, cornerRadius, cornerRadius);

            path.Flatness = 0.05f;

            var shape = SCNShape.Create(path, 20);

            shape.ChamferRadius = 0.0f;

            var node = SCNNode.Create();

            node.Geometry = shape;

            // create an image and fill with the color and text
            var textureSize = new CGSize();

            textureSize.Width  = (float)Math.Ceiling((double)frame.Size.Width * 1.5);
            textureSize.Height = (float)Math.Ceiling((double)frame.Size.Height * 1.5);

            var texture = new NSImage(textureSize);

            texture.LockFocus();

            var drawFrame = new CGRect(0, 0, textureSize.Width, textureSize.Height);

            nfloat hue, saturation, brightness, alpha;

            (color.UsingColorSpace(NSColorSpace.DeviceRGBColorSpace)).GetHsba(out hue, out saturation, out brightness, out alpha);
            var lightColor = NSColor.FromDeviceHsba(hue, saturation - 0.2f, brightness + 0.3f, alpha);

            lightColor.Set();

            NSGraphics.RectFill(drawFrame);

            NSBezierPath fillpath = null;

            if (cornerRadius == 0 && centered == false)
            {
                //special case for the "labs" slide
                drawFrame.Offset(0, -2);
                fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius);
            }
            else
            {
                drawFrame.Inflate(-3, -3);
                fillpath = NSBezierPath.FromRoundedRect(drawFrame, cornerRadius, cornerRadius);
            }

            color.Set();
            fillpath.Fill();

            // draw the title if any
            if (title != null)
            {
                if (titleAttributes == null)
                {
                    var paraphStyle = new NSMutableParagraphStyle();
                    paraphStyle.LineBreakMode     = NSLineBreakMode.ByWordWrapping;
                    paraphStyle.Alignment         = NSTextAlignment.Center;
                    paraphStyle.MinimumLineHeight = 38;
                    paraphStyle.MaximumLineHeight = 38;

                    var font = NSFont.FromFontName("Myriad Set Semibold", 34) != null?NSFont.FromFontName("Myriad Set Semibold", 34) : NSFont.FromFontName("Avenir Medium", 34);

                    var shadow = new NSShadow();
                    shadow.ShadowOffset     = new CGSize(0, -2);
                    shadow.ShadowBlurRadius = 4;
                    shadow.ShadowColor      = NSColor.FromDeviceWhite(0.0f, 0.5f);

                    titleAttributes = new NSMutableDictionary();
                    titleAttributes.SetValueForKey(font, NSAttributedString.FontAttributeName);
                    titleAttributes.SetValueForKey(NSColor.White, NSAttributedString.ForegroundColorAttributeName);
                    titleAttributes.SetValueForKey(shadow, NSAttributedString.ShadowAttributeName);
                    titleAttributes.SetValueForKey(paraphStyle, NSAttributedString.ParagraphStyleAttributeName);

                    var centeredParaphStyle = (NSMutableParagraphStyle)paraphStyle.MutableCopy();
                    centeredParaphStyle.Alignment = NSTextAlignment.Center;

                    centeredTitleAttributes = new NSMutableDictionary();
                    centeredTitleAttributes.SetValueForKey(font, NSAttributedString.FontAttributeName);
                    centeredTitleAttributes.SetValueForKey(NSColor.White, NSAttributedString.ForegroundColorAttributeName);
                    centeredTitleAttributes.SetValueForKey(shadow, NSAttributedString.ShadowAttributeName);
                    centeredTitleAttributes.SetValueForKey(paraphStyle, NSAttributedString.ParagraphStyleAttributeName);
                }

                var attrString = new NSAttributedString(title, centered ? centeredTitleAttributes : titleAttributes);
                var textSize   = attrString.Size;

                //check if we need two lines to draw the text
                var twoLines = title.Contains("\n");
                if (!twoLines)
                {
                    twoLines = textSize.Width > frame.Size.Width && title.Contains(" ");
                }

                //if so, we need to adjust the size to center vertically
                if (twoLines)
                {
                    textSize.Height += 38;
                }

                if (!centered)
                {
                    drawFrame.Inflate(-15, 0);
                }

                //center vertically
                var dy = (drawFrame.Size.Height - textSize.Height) * 0.5f;
                var drawFrameHeight = drawFrame.Size.Height;
                drawFrame.Size = new CGSize(drawFrame.Size.Width, drawFrame.Size.Height - dy);
                attrString.DrawString(drawFrame);
            }

            texture.UnlockFocus();

            //set the created image as the diffuse texture of our 3D box
            var front = SCNMaterial.Create();

            front.Diffuse.Contents        = texture;
            front.LocksAmbientWithDiffuse = true;

            //use a lighter color for the chamfer and sides
            var sides = SCNMaterial.Create();

            sides.Diffuse.Contents  = lightColor;
            node.Geometry.Materials = new SCNMaterial[] {
                front,
                sides,
                sides,
                sides,
                sides
            };

            return(node);
        }