【问题标题】:How to add a circular mask to a UIImageview and change the frame and centers while doing so?如何在 UIImageview 中添加圆形遮罩并更改框架和中心?
【发布时间】:2013-03-09 05:43:09
【问题描述】:

我想给 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,只需运行它就可以看到我的问题并告诉我如何解决问题。

【问题讨论】:

标签: ios uiimageview calayer uiviewanimation cashapelayer


【解决方案1】:

希望这会有所帮助

    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;

【讨论】:

  • 这并没有解决最初的问题,即在使用蒙版时如何将帧更改为UIImageView 的动画...
  • 我发现这段代码非常方便,因为我需要一个偏离中心的圆形遮罩来创建我正在创建的视图。首先,我使用 layer.cornerRadius 在 Interface Builder 中使视图呈圆形。然后我在 Bezier 路径中使用了这个带有负 Y 值的代码来为它创建一个遮罩。最终的形状看起来很像美式足球,这正是我所需要的。
【解决方案2】:

好的,因此,由于我的案例中的中心发生了变化,因此使用面罩并无济于事。所以简单干净的方法是有一个自定义的 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 作为基础 类。

【讨论】:

  • 自定义 UIImageView 解决方案是我以前使用的,因此该解决方案适用于我。它看起来也更接近 iOS 7 的功能
  • 你也可以改变遮罩层的中心。
  • 请注意,您的评论并不完全正确——UIView 的这个子类必须有一个 UIImage 作为属性,而不是一个 UIImageView
猜你喜欢
  • 1970-01-01
  • 2014-07-20
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多