Ios 如何向UIImageview添加圆形遮罩,并在执行此操作时更改边框和中心?
我想在UIImageVIew中添加一个圆形遮罩。下面是我用来添加掩码的函数Ios 如何向UIImageview添加圆形遮罩,并在执行此操作时更改边框和中心?,ios,uiimageview,calayer,uiviewanimation,cashapelayer,Ios,Uiimageview,Calayer,Uiviewanimation,Cashapelayer,我想在UIImageVIew中添加一个圆形遮罩。下面是我用来添加掩码的函数 - (void) addMaskToBounds:(CGRect) maskBounds { CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init]; CGPathRef maskPath = CGPathCreateWithEllipseInRect(maskBounds, NULL); maskLayer.bounds = maskBoun
- (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上创建了一个演示项目,只需运行它来查看我的问题,并让我知道如何解决问题。好的,因为我的案例中的中心发生了变化,所以使用掩码并没有帮助。因此,简单而干净的方法是使用自定义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作为基础
班级
希望这会有所帮助
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解决方案是我以前使用的,所以这个解决方案对我来说是合适的。它看起来更接近iOS 7的功能。您也可以更改遮罩层的中心。请注意,您的注释不太正确--UIView的这个子类必须有一个UIImage作为属性,不是UIImageView这并不能解决使用遮罩时如何将帧更改动画化为
UIImageView
的初始问题……我发现这段代码非常方便,因为我创建的视图需要一个偏心圆形遮罩。首先,我使用layer.cornerRadius在Interface Builder中使视图成为圆形。然后,我在贝塞尔路径中使用Y值为负值的代码为其创建了一个遮罩。最终的形状看起来很像美式足球,这正是我所需要的。