In one of my methods i have this code:
-(void)myMethod {
UIBezierPath *circle = [UIBezierPath
bezierPathWithOvalInRect:CGRectMake(75, 100, 200, 200)];
}
How do i get it to show on the view?
I tried addSubview but it gave me an incompatible type error
because its expecting a UIView.
I'm sure this must be simple.
Thanks
Drawing is the exclusive provision of views. Make a custom view, give it your path, and implement the view's
drawRect:
method to fill and/or stroke the path.Just thought I'd add that you don't have to necessarily draw this in a UIView's "drawRect:" method. You can draw it anywhere you'd like to provided you do it inside of a UIGraphics image context. I do this all of the time when I don't want to create a subclass of UIView. Here's a working example:
Now just add the UIImageView as a subview.
Also, you can use this for other drawing too. Again, after a little bit of setup, it works just like the drawRect: method.
Edit: One thing I should add is that for any modern day drawing of this kind, you should be swapping out
for
This will draw your graphics correctly for retina and non retina displays.
FYI,
UIGraphicsBeginImageContext(size)
is equivalent toUIGraphicsBeginImageContextWithOptions(size, FALSE, 1.f)
which is fine for none retina displays that may have some transparency.However, if you don't need transparency, it is more optimized to pass in TRUE for the opaque argument.
The safest and recommended way of drawing is to pass in
[[UIScreen mainScreen]scale]
as the scale argument.So for the example(s) above, you would use this instead:
For more info, check out Apple's docs.
You can also add UIBezierPath to UIView without subclassing by using a CAShapeLayer.
For example, to add your path as a 3pt white line centered in a UIView:
In Swift 2.0:
You can draw it using either
fill
orstroke
methods for example in custom view'sdrawInRect:
implementation: