ios - 带有边框和圆角的 UIImageView,图像从边框边缘弹出

标签 ios objective-c uiimageview

我正在尝试制作一个带有圆角和白色边框的 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

这是结果:

enter image description here

看起来不错,但是从这里可以看出有一个问题:

enter image description here

图像从边框边缘弹出,我该如何避免这个问题?我怎样才能准确地在边界的边缘切割图像?

最佳答案

也许更好的解决方案根本不涉及制作另一个 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/

相关文章:

ios - 如何定位一个SCNNode来覆盖整个SCNView?

iphone - 如何获取保存在文档目录中的视频的缩略图

ios - 旋转图像的碰撞检测

ios - 如何将图像添加到 UIImageView?

ios - 如何为不同的屏幕尺寸设置不同的自动布局约束

ios - didReceiveRemoteNotification 不在后台工作

ios - 核心数据拉动变化

ios - 使用 Core Bluetooth 时出现问题

ios - 从 iOS 应用程序向蓝牙扬声器播放现场声音

iphone - 使用 8 个图像在 UIImageView 周围创建边框