如何在UIImageview中添加圆形蒙版并更改框架和中心?

时间:2013-03-09 05:43:10

标签: ios uiimageview calayer uiviewanimation cashapelayer

我想为UIImageVIew添加一个圆形遮罩。这是用于添加蒙版的函数..

- (void) addMaskToBounds:(CGRect) maskBounds
{
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];

    CGPathRef maskPath = CGPathCreateWithEllipseInRect(maskBounds, NULL);
    maskLayer.bounds = maskBounds;
    [maskLayer setPath:maskPath];
    [maskLayer setFillColor:[[UIColor blackColor] CGColor]];
    maskLayer.position = CGPointMake(maskBounds.size.width/2, maskBounds.size.height/2);

    [self.imageView.layer setMask:maskLayer];
}

能够添加蒙版,但问题出现了,因为我正在更改图像框架并将其随之居中。根据用户操作放大图像并缩小图像。因此,当小和扩大时,我将不得不添加两次。因此,由于动画帧的变化,动画图像变得扭曲或移位。我该如何克服这个问题?

我想最好用一个示例项目来解释。在这里,我在GitHub上创建了一个Demo项目https://github.com/akshaynhegde/MaskImage,只需运行它来查看我的问题并让我知道如何解决问题。

2 个答案:

答案 0 :(得分:22)

希望这会有所帮助

    CAShapeLayer *circle = [CAShapeLayer layer];
    // Make a circular shape
    UIBezierPath *circularPath=[UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, _imgView.frame.size.width, _imgView.frame.size.height) cornerRadius:MAX(_imgView.frame.size.width, _imgView.frame.size.height)];

    circle.path = circularPath.CGPath;

    // Configure the apperence of the circle
    circle.fillColor = [UIColor blackColor].CGColor;
    circle.strokeColor = [UIColor blackColor].CGColor;
    circle.lineWidth = 0;

    imgViewToClipCircular.layer.mask=circle;

答案 1 :(得分:4)

好的,所以既然我的案例中心发生了变化,使用面具并不是很有帮助。因此,简单而干净的方法是使用自定义UiImageView并剪切绘制路径。

为此,子类UIView并在其中绘制图像并剪切路径。这是覆盖drawRect函数,

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextAddEllipseInRect(context, self.bounds);
    CGContextClip(context);
    //The subclass of UIView has a UIImageview as property
    [_image drawInRect:rect];    
}

仅供参考,您不能继承UIImageView本身并覆盖drawRect,因为它不会调用drawRect

  

优化UIImageView类以将其图像绘制到显示器。   UIImageView不会调用drawRect:一个子类。如果您的子类需要   自定义绘图代码,建议您使用UIView作为基础   类。