Drawing a transparent circle on top of a UIImage - iPhone SDK

前端 未结 4 534
轮回少年
轮回少年 2021-02-11 07:19

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

相关标签:
4条回答
  • 2021-02-11 08:03

    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];
    
    0 讨论(0)
  • 2021-02-11 08:05

    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];
    
    0 讨论(0)
  • 2021-02-11 08:10

    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.

    0 讨论(0)
  • 2021-02-11 08:13

    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];
    
    0 讨论(0)
提交回复
热议问题