When the system is to display a view (UIView), it sends DrawRect (RECT:) messages to the view. So, if we need to draw on a view, we can implement it inside the DrawRect method.
1, filled rectangle with solid color
The following creates a rectangular uiview, coordinate (50,50) with a long width of 100. The interior uses a green fill.
The code is as follows |
Copy Code |
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, draw the rounded rectangle while adding the outline of the outer border
(1) When you stroke a path, the contour line is drawn on the path. Because the contour line width is 3, in order for the contour line to not be trimmed by the edges, the rectangle is indented a point by using the Cgrectinset function to keep the center point unchanged.
(2) rewrite the init (frame:cgrect) method to set the background color to transparent, otherwise the background is black (four rounded transparent parts will show black)
The code is as follows |
Copy Code |
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) Set the background color to transparent 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 () } } |