3
votes

I would like to draw a rectangle with rounded corners, but I'm pretty new to the platform and it's really different from, for example, WPF or UWP.

I've seen examples in Objective-C, but I don't know how to translate to Xamarin.iOS.

1

1 Answers

2
votes

A rounded filled rectangle path:

var rectanglePath = UIBezierPath.FromRoundedRect(new CGRect(0.0f, 0.0f, 200.0f, 100.0f), 50.0f);
UIColor.Red.SetFill();
rectanglePath.Fill();

Using an ImageContext to create a UIImage:

UIGraphics.BeginImageContext(new CGSize(200.0f, 100.0f));
var rectanglePath = UIBezierPath.FromRoundedRect(new CGRect(0.0f, 0.0f, 200.0f, 100.0f), 50.0f);
UIColor.Red.SetFill();
rectanglePath.Fill();
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();

Via UIView subclass:

public class RoundedBox : UIView
{
    public RoundedBox()
    {
    }

    public RoundedBox(Foundation.NSCoder coder) : base(coder)
    {
    }

    public RoundedBox(Foundation.NSObjectFlag t) : base(t)
    {
    }

    public RoundedBox(IntPtr handle) : base(handle)
    {
    }

    public RoundedBox(CoreGraphics.CGRect frame) : base(frame)
    {
    }

    public override void Draw(CGRect rect)
    {
        var rectanglePath = UIBezierPath.FromRoundedRect(rect, 50.0f);
        UIColor.Red.SetFill();
        rectanglePath.Fill();
    }
}