Search code examples
iosuiviewcore-graphicsdrawrectcgcontext

Trying to draw a filled circle but it has got a black background


I want to draw a circle with a certain color, which fills out the whole circle. I'm using auto layout to determine the size of the circle. If I'm doing this the circle is drawn but the background color is black. It should be a clear color so that the background can shine through and the circle should be round of course. This is my code in C#, but it isn't that much difference to Objective-C.

public class Circle : UIView
    {
        private UIColor color;

        public Circle ()
        {
            this.color = UIColor.Red;
        }

        public override void Draw (RectangleF rect)
        {
            base.Draw (rect);

            this.BackgroundColor = UIColor.Clear;

            float red = 0;
            float green = 0;
            float blue = 0;
            float alpha = 0;
            color.GetRGBA (out red, out green, out blue, out alpha);

            float lineWidth = 2.0f;
            RectangleF borderRect = RectangleF.Inflate (rect, -lineWidth/2, -lineWidth/2);

            // Get the context
            CGContext context = UIGraphics.GetCurrentContext ();

            // Set the border width
            context.SetLineWidth (lineWidth);

            // Set the circle fill color
            context.SetRGBFillColor (red, green, blue, alpha);

            // Set the circle border color
            context.SetRGBStrokeColor (red, green, blue, alpha);

            // Fill the circle with the fill color
            context.FillEllipseInRect (borderRect);

            // Draw the circle border
            //context.StrokeEllipseInRect (borderRect);
        }
    }
}

The circle is slightly smaller than the UIView so that is drawn correctly not touching the edges (and so cutting of some parts).

But the background is black as you can see here: circle with black background

How can I draw a filled circle?


Solution

  • Seems that I have to put this

    this.BackgroundColor = UIColor.Clear;
    

    into the constructor. Now I don't have a black background anymore.

    It seems also that it is sufficient to use these lines of code for drawing:

    context.AddEllipseInRect (rect);
    context.SetFillColor (color.CGColor);
    context.FillPath ();