我正在尝试制作一个带有圆角和白色边框的 UIImageView,我已经将 UIImageView 子类化,这是代码:
MyUIImageView.h
@interface MyUIImageView : UIImageView
@end
MyUIImageView.m
@implementation MyUIImageView
-(void)layoutSubviews
{
self.layer.cornerRadius = CGRectGetWidth(self.frame)/2.f;
self.layer.borderColor = [[UIColor whiteColor] CGColor];
self.layer.borderWidth = kLineWidth;
self.layer.masksToBounds = YES;
self.clipsToBounds = YES;
self.contentMode = UIViewContentModeScaleAspectFill;
self.backgroundColor = [UIColor colorWithRed:0.82 green:0.82 blue:0.83 alpha:1];
}
@end
这是结果:
看起来不错,但是从这里可以看出有一个问题:
图像从边框边缘弹出,我该如何避免这个问题?我怎样才能准确地在边界的边缘切割图像?
最佳答案
也许更好的解决方案根本不涉及制作另一个 View - 使用两个 View 会大大增加动画等的复杂性,更不用说跟踪和操作这两个 View 的开销了。
我会创建一个形状图层并将其添加为子图层。像这样:
CAShapeLayer border = [[CAShapeLayer alloc] init];
border.path = [UIBezierPath bezierPathWithRoundedRect: self.bounds cornerRadius: self.layer.cornerRadius];
border.strokeColor = [UIColor whiteColor];
border.fillColor = [UIColor clearColor];
self.layer.addSublayer(border)
这样做的好处是,如果您愿意,您可以将它作为一个方法添加到您的 UIImageView 子类中。只要您不更改基础对象的框架,您就可以为对象添加边框而不必理会它。变换等会影响子层,因此您可以缩放、旋转等并且没有毛边。
希望这对您有所帮助!
关于ios - 带有边框和圆角的 UIImageView,图像从边框边缘弹出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25467176/