Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best technique to render circles in iOS?

When rendering opaque non-gradient circular shapes of uniform color in iOS, there seem to be three possible techniques:

Using images like circle-icon.png and [email protected]. Then, one may implement the following code to have iOS automagically render the appropriate size:

UIImage *image = [UIImage imageNamed:@"circle-icon"];
self.closeIcon = [[UIImageView alloc] initWithImage:image];
self.closeIcon.frame = CGRectMake(300, 16, image.size.width, image.size.height);

Rendering rounded corners and using layers, like so:.

self.circleView = [[UIView alloc] initWithFrame:CGRectMake(10,20,100,100)];
circleView.alpha = 0.5;
self.circleView.layer.cornerRadius = 50;
self.circleView.backgroundColor = [UIColor blueColor];

Using the native drawing libraries, with something like CGContextFillEllipseInRect

What are the exact performance and maintenance tradeoffs of these 3 approaches?

like image 217
zealoushacker Avatar asked Mar 22 '23 17:03

zealoushacker


1 Answers

You're overlooking another very logical alternative, UIBezierPath and CAShapeLayer. Create UIBezierPath that is a circle, create a CAShapeLayer that uses that UIBezierPath, and then add that layer to your view/layer hierarchy.

  1. Add the QuartzCore framework to your project.

  2. Second, import the appropriate header:

    #import <QuartzCore/QuartzCore.h>
    
  3. And then you can add a CAShapeLayer to your view's layer:

    UIBezierPath *path = [UIBezierPath bezierPath];
    [path addArcWithCenter:CGPointMake(self.view.bounds.size.width / 2.0, self.view.bounds.size.height / 2.0) radius:self.view.bounds.size.width * 0.40 startAngle:0 endAngle:M_PI * 2.0 clockwise:YES];
    CAShapeLayer *layer = [[CAShapeLayer alloc] init];
    layer.path = [path CGPath];
    layer.fillColor = [[UIColor blueColor] CGColor];
    [self.view.layer addSublayer:layer];
    

I think that either a CoreGraphics implementation, or this CAShapeLayer implementation make more sense than PNG files or UIView objects with rounded corners.

like image 83
Rob Avatar answered Apr 01 '23 14:04

Rob