vendredi 10 juin 2016

Xamarin iOS CGPath draw polygon with curved/rounded corners


I'm trying to create a class that draws a polygon in a custom UIView subclass. I have it working, but now I want to smooth the corners by rounding them off and I'm not sure how to do that. Here is what I have so far:

public class MyView : UIView
{
    private List<CGPoint> points;

    public MyView(CGRect frame, List<CGPoint> points) : base (frame)
    {
        this.points = points;
    }

    public override Draw (CGRect rect)
    {
        CGContext context = UIGraphics.GetCurrentContext();

        context.SetLineWidth(2);
        UIColor.Black.SetStroke();
        UIColor.Green.SetFill();

        CGPath path = new CGPath();
        path.AddLines(points.ToArray());
        path.CloseSubpath();

        context.AddPath(path);
        context.Clip();

        using (CGColorSpace rgb = CGColorSpace.CreateDeviceRGB())
        {
            CGGradient gradient = new CGGradient (rgb, new CGColor[]
            {
                new CGColor(0, 1, 0),
                new CGColor(0, 0.5f, 0),
                new CGColor(0, 1, 0),
                new CGColor(0, 0.5f, 0)
            });

            context.DrawLinearGradient(gradient,
                new CGPoint (path.BoundingBox.Left, path.BoundingBox.Top), 
                new CGPoint (path.BoundingBox.Right, path.BoundingBox.Bottom), 
                CGGradientDrawingOptions.DrawsBeforeStartLocation);
        }
    }
}

With the points I'm throwing in I get this:

enter image description here

I've tried using path.AddCurveToPoint and path.AddArc but I can't seem to get them to work the way I want. Any help would be appreciated.


Aucun commentaire:

Enregistrer un commentaire