我有这个用于UIVIew的代码
override func drawRect(rect: CGRect) {
let toolbarSize = CGFloat(UIDevice.currentDevice().userInterfaceIdiom == .Pad ? 0 : 54)
let width = CGRectGetWidth(self.frame)
let height = CGRectGetHeight(self.frame) - toolbarSize
let heightSpan = floor(height / 2 - self.cropSize.height / 2)
let widthSpan = floor(width / 2 - self.cropSize.width / 2)
// fill outer rect
UIColor(red: 0, green: 0, blue: 0, alpha: 0.5).set()
UIRectFill(self.bounds)
// fill inner border
UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).set()
UIRectFrame(CGRectMake(widthSpan - 2, heightSpan - 2, self.cropSize.width + 4,
self.cropSize.height + 4))
// fill inner rect
UIColor.clearColor().set()
UIRectFill(CGRectMake(widthSpan, heightSpan, self.cropSize.width, self.cropSize.height))
}这会给我的UIView画一个白色边框的矩形,我想要添加一个圆角半径来画一个圆。
有可能做到这一点吗?
发布于 2016-01-25 23:36:08
这对我来说很好
someImageView.layer.borderWidth = 1
someImageView.layer.borderColor = UIColor.blackColor().CGColor
someImageView.layer.cornerRadius = someImageView.frame.height/2
someImageView.clipsToBounds = true发布于 2016-01-25 23:33:49
带圆角的矩形:使用路径。
除非您希望使用layer.cornerRadius将圆角应用于整个视图(最简单)或子层(最灵活),否则可以使用UIBezierPath绘制roundedRect。
cornerRadius为1/2的正方形roundedRect的高度最终是一个圆或一个圆盘。
let path = UIBezierPath(roundedRect: innerRect,cornerRadius: 10)
path.fill()3 roundedRect随心所欲:
let regular = UIBezierPath(roundedRect: CGRect, cornerRadius: CGFloat)
let irregular = UIBezierPath(roundedRect: CGRect,
byRoundingCorners: UIRectCorner, cornerRadii: CGSize)
let oval = UIBezierPath(ovalInRect: CGRect)边框使用path.stroke(),内容使用path.fill()。
drawRect上下文中的示例:
// fill inner rect
UIColor.clearColor().set()
let innerRect = CGRectMake(widthSpan, heightSpan,
self.cropSize.width, self.cropSize.height)
// replace UIRectFill(innerRect) by:
let path = UIBezierPath(roundedRect: innerRect, cornerRadius: 10)
path.fill()受此excellent讨论的启发:
UIBezierPath* path = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, 100, 100)
cornerRadius: 10];
path.lineWidth = 1;
[UIColor.clearColor setStroke];
[path stroke];发布于 2016-01-26 07:08:33
您可以在awakeFromNib中使用代码。下面的代码对我来说非常好用
- (void)awakeFromNib {
// Initialization code
self.authorAvatar.layer.cornerRadius = self.authorAvatar.frame.size.width/2;
self.authorAvatar.clipsToBounds = YES;
}我在自定义单元格中使用它。你也可以在自定义视图中使用相同的代码。
https://stackoverflow.com/questions/34995677
复制相似问题