简体   繁体   中英

UIBezierPath - byRoundingCorners - Rect

I have a very easy view controller..

import UIKit

class ViewController: UIViewController {

    let f = TstKocka(frame: CGRectMake(100,100, 150, 150))

    override func viewDidLoad() {
        super.viewDidLoad()

        view.addSubview(f)

    }

}

And I have a UIView class:

class TstKocka: UIView {


    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func drawRect(rect: CGRect) {

        var path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners, cornerRadii: CGSize(width: 2.0, height: 2.0))

        path.lineWidth = 1.0
       path.stroke()

    }

}

And I'm trying to create a rounded rect but I don't know how to do. I've read lot of tutorials but none of them worked for me.Please help me.

since you are not providing a fill color i guess your rect shall have a clear color. to make that work change your initwithframe to the following:

override init(frame: CGRect) {
    super.init(frame: frame)
    opaque = false
}

then increase cornerradii value (to 20.0, 20.0 for example) to see that it works! :)

EDIT

filling is actually as simple as stroking:

let path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners, cornerRadii: CGSize(width: 20.0, height: 20.0))
path.lineWidth = 1.0

UIColor.blueColor().setFill() // or whatever fill color you like
path.fill()

UIColor.redColor().setStroke()
path.stroke()

If you are trying to create a rounded rect view that clips the content, you should use layer masks or the simple -cornerRadius property on the views layer, setting also the -borderWidth .
If you just want a view background rounded rect, before stroking you should set the stroke color.
I don't know swift but in objC could be something like this

- (void) drawRect:(CGRect) rect {
 UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:5.0];
 [[UIColor redColor] setStroke];
 [bezierPath stroke];
}

In Swift probably:

  override func drawRect(rect: CGRect) {
        let path = UIBezierPath(roundedRect: rect, byRoundingCorners: UIRectCorner.AllCorners, cornerRadii: CGSize(width: 2.0, height: 2.0))
    UIColor.redColor().setStroke() 
        path.lineWidth = 1.0
       path.stroke()

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM