带圆角的 drawRect

Luc*_*tti 4 core-graphics ios swift

我有这个代码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))
}
Run Code Online (Sandbox Code Playgroud)

这会在 my 上绘制一个带有白色边框的矩形UIView,我想添加一个圆角半径来绘制一个圆。

是否有可能做到这一点?

Swi*_*ect 6

带圆角的矩形:使用路径。

除非您想使用 将圆角应用到整个视图(最简单)或子图层(最灵活)layer.cornerRadius,否则您可以使用绘制roundedRectUIBezierPath。高度为1/2 的
方形roundedRectcornerRadius最终会成为一个圆或一个圆盘。

let path = UIBezierPath(roundedRect: innerRect,cornerRadius: 10)
path.fill()
Run Code Online (Sandbox Code Playgroud)

3 个 roundedRect 可供您使用:

let regular   = UIBezierPath(roundedRect: CGRect, cornerRadius: CGFloat)
let irregular = UIBezierPath(roundedRect: CGRect,
                        byRoundingCorners: UIRectCorner, cornerRadii: CGSize)
let oval      = UIBezierPath(ovalInRect: CGRect)
Run Code Online (Sandbox Code Playgroud)

用于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()
Run Code Online (Sandbox Code Playgroud)

受到这次精彩讨论的启发:

UIBezierPath* path = [UIBezierPath bezierPathWithRoundedRect: CGRectMake(0, 0, 100, 100)
             cornerRadius: 10];
path.lineWidth = 1;
[UIColor.clearColor setStroke];
[path stroke];
Run Code Online (Sandbox Code Playgroud)


Dey*_*een 5

这对我很有用

    someImageView.layer.borderWidth = 1
    someImageView.layer.borderColor = UIColor.blackColor().CGColor
    someImageView.layer.cornerRadius = someImageView.frame.height/2
    someImageView.clipsToBounds = true
Run Code Online (Sandbox Code Playgroud)