iOS Clean corners for rounded profile image

2020-02-13 02:21发布

So I followed an AppCoda tutorial on rounding the corners of a profile image, and it worked fine, except for one thing. Wherever the image was rounded, there is a bit of bleed-through from the image (especially if a white border is used).

enter image description here

self.imageview.image = image
self.imageview.layer.cornerRadius = 10.0
self.imageview.layer.borderWidth = 3.0
self.imageview.layer.borderColor = UIColor.whiteColor().CGColor
self.imageview.clipsToBounds = true

enter image description here

标签: ios uiview
3条回答
一纸荒年 Trace。
2楼-- · 2020-02-13 03:06

A simple solution is that you can enlarge layer's bounds a little bit to cover the edge of view's image:

CGFloat offset = 1.f; // .5f is also good enough
self.imageview.image = image;
self.imageview.layer.cornerRadius = 10.0;
self.imageview.layer.borderWidth = 3.0 + offset;
self.imageview.layer.borderColor = UIColor.whiteColor().CGColor;
self.imageview.layer.masksToBounds = YES;

[self.imageview.layer setBounds:CGRectMake(-offset,
                                           -offset,
                                           CGRectGetWidth(self.imageview.frame)  + offset * 2.f,
                                           CGRectGetHeight(self.imageview.frame) + offset * 2.f)];
查看更多
何必那么认真
3楼-- · 2020-02-13 03:20

You could create a mask over the rectangle. This seems to give clean edges, at least in Playground. Here is the code, but you will need to modify it a bit to get rounded inner rect.

// simple red rect
var view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.redColor()
view.layer.borderColor = UIColor.whiteColor().CGColor
view.layer.borderWidth = 6.0

// path for the mask
let rectanglePath = UIBezierPath(roundedRect:view.bounds, cornerRadius: 20)
// applying the mask over the view
let maskLayer = CAShapeLayer()
maskLayer.frame = view.bounds
maskLayer.path = rectanglePath.CGPath
view.layer.mask = maskLayer
查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-13 03:22

You can also add a mask which is inset a little, if you want:

let path = UIBezierPath(roundedRect: CGRectInset(imageView.bounds, 0.5, 0.5), cornerRadius: 10.0)
let mask = CAShapeLayer()
mask.path = path.CGPath
imageview.layer.mask = mask
查看更多
登录 后发表回答