Swift - 在UIView上绘制矩形(直角,圆角,带边框)
当系统要显示一个视图(UIView)时,它会向视图发送drawRect(rect:)消息。所以,如果我们需要在视图上进行绘制,则可以在drawRect方法内部实现。
2,绘制圆角矩形,同时添加外部边框轮廓
1,用纯色填充的矩形
下面创建一个长宽都为100的矩形UIView,坐标(50,50)。其内部使用绿色填充。
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let viewRect = CGRect(x: 50, y: 50, width: 100, height: 100) let view1 = MyCanvas(frame: viewRect) self.view.addSubview(view1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } class MyCanvas: UIView { override func drawRect(rect: CGRect) { UIColor.greenColor().setFill() let path = UIBezierPath(rect: self.bounds) path.fill() } }
2,绘制圆角矩形,同时添加外部边框轮廓
(1)在对一个路径描边时,轮廓线是在路径上绘制的。由于设置轮廓线宽度为3,为了让轮廓线不会被边缘裁去一部分,使用 CGRectInset函数保持中心点不变的情况下矩形内缩一个点。
(2)重写init(frame: CGRect) 方法,将背景色设为透明,否则背景是黑色的(四个圆角透明部分会显示黑色)
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let viewRect = CGRect(x: 50, y: 50, width: 100, height: 100) let view1 = MyCanvas(frame: viewRect) self.view.addSubview(view1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } class MyCanvas: UIView { override init(frame: CGRect) { super.init(frame: frame) //把背景色设为透明 self.backgroundColor = UIColor.clearColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { let pathRect = CGRectInset(self.bounds, 1, 1) let path = UIBezierPath(roundedRect: pathRect, cornerRadius: 10) path.lineWidth = 3 UIColor.greenColor().setFill() UIColor.blueColor().setStroke() path.fill() path.stroke() } }