0

I am drawing a circle in my custom UIView's drawRect:

- (void)drawRect:(CGRect)rect {
  ...
  UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:rect];
  [UIColor.whiteColor setStroke];
  ovalPath.lineWidth = 1;
  [ovalPath stroke];
}

The oval is always clipped on the edge. How can I avoid the clipping? Is insetting the rect the only way?

Boon
  • 40,656
  • 60
  • 209
  • 315

1 Answers1

5

CG draws the stroke centered on the path -- half inside the path, half outside the path. Therefore, part of the stroke is outside of your view, and you don't see it.

Inset the rect by half the stroke width.

CGRect rectToStroke = CGRectInset(rect, 0.5, 0.5);
UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect: rectToStroke];

Anything you draw inside of -drawRect: using CG or UIKit goes into a bitmap context which is the size of your view's bounds.

If you need to show something bigger than bounds.size, you have two options: make the view's bounds bigger, or draw via some other method, such as:

  1. add a subview which is bigger (but it will appear on top of your view, so you'll need to make it partially transparent)
  2. add a CALayer or CAShapeLayer to your view's layer (with the same caveat)
  3. set your view's layer's borderWidth to draw a border on top of the contents

(For all of these, you may find that you also need to set your view's clipsToBounds property to NO, if it isn't already.)

Kurt Revis
  • 27,695
  • 5
  • 68
  • 74