views:

315

answers:

4

I am having a lot of trouble trying to find out how to draw a transparent circle on top of a UIImage within my UIImageView. Google-ing gives me clues, but I still can't find a working example.

Are there any examples that anyone knows of that demonstrate this?

A: 

One way would be to add a CAShapeLayer with a circular path, either directly to the layer of the UIImageView or as the layer of a new UIView that is added to the UIImageView.

If you actually want to modify the image, then create a mutable copy of it by drawing it into a CGBitmapContext then creating a new image from the modified bitmap.

CGPathRef circlePath = CGPathCreateMutable();
CGPathAddEllipseInRect( circlePath , NULL , CGRectMake( 0,0,20,20 ) );
CAShapeLayer *circle = [[CAShapeLayer alloc] init];
circle.path = circlePath;
circle.opacity = 0.5;
[myImageView.layer addSublayer:circle];
CGPathRelease( circlePath );
[circle release];
drawnonward
A: 

You can implement a custom sub-class of UIView that draws your image and then the circle in the drawRect method:

@interface CircleImageView : UIView {
    UIImage * m_image;
    CGRect m_viewRect;

    // anything else you need in this view?
} 

Implementation of drawRect:

- (void)drawRect:(CGRect)rect {

    // first draw the image
    [m_image drawInRect:m_viewRect blendMode:kCGBlendModeNormal alpha:1.0];

    // then use quartz to draw the circle
    CGContextRef context = UIGraphicsGetCurrentContext ()

    // stroke and fill black with a 0.5 alpha
    CGContextSetRGBStrokeColor(context, 1.0, 1.0, 1.0, 0.5);
    CGContextSetRGBFillColor(context, 1.0, 1.0, 1.0, 0.5);

    // now draw the circle
    CGContextFillEllipseInRect (context, m_viewRect);
}

You will need to set up the *m_viewRect* and *m_image* member functions on init.

Cannonade
+1  A: 

This has got to be the simplest solution:

CGFloat r = 150;

UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,1.5*r,1.5*r)];
lbl.text = @"●";
lbl.transform = CGAffineTransformMakeTranslation(0.0f, -r/6);
lbl.textAlignment = UITextAlignmentCenter;
lbl.backgroundColor = [UIColor clearColor];
lbl.textColor = [UIColor redColor];
lbl.font = [UIFont systemFontOfSize:2*r];
lbl.alpha = 0.5;
lbl.center = self.view.center;
[self.view addSubview:lbl];
mvds
+1 for left field awesome! :P
Cannonade
even with baseline correction!
mvds
Check mine for a simpler method :-P (less code).
iamj4de
+1  A: 

Easiest way is simply to create a semi-transparent square UIView, then set the cornerRadius of its layer to be half of its width/height. Something like:

UIView *squareView = [[UIView alloc] initWithFrame:CGRectMake(0,0,100,100)];
squareView.alpha = 0.5;
squareView.layer.cornerRadius = 50;
...
[squareView release];
iamj4de
You forgot squareView.clipsToBounds = YES; without it, this will not work.
bstahlhood
Only if you want to add another view on top of it, but that's a different story.
iamj4de