swift - 畫圖 - 畫矩形,虛線,圓和半圓


 

 

 

 

 

import UIKit

class JYJYBouncedCouponsViewCellBgView: UIView {

    //一定要在這里設置 背景色, 不要再draw里面設置, 
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = UIColor.clear
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        // 獲取上下文
        guard let context = UIGraphicsGetCurrentContext() else {
            return
        }
        
        //畫一個矩形, 帶圓角的,填充色為FFE4C3,切圓角5
        UIColor.init(hexColor: "FFE4C3").set()
        context.addPath(UIBezierPath(roundedRect: rect, cornerRadius: 5).cgPath)
        context.fillPath()
        //填充色setFillColor , 畫線的顏色setStrokeColor
//        context.setFillColor(UIColor.init(hexColor: "FFE4C3").cgColor)
        
        // 畫虛線
        /**設置起始和結束位置**/
        let startPointX: CGFloat = rect.size.width - 97
        let staerPointY: CGFloat = 0
        let endPointX: CGFloat = rect.size.width - 97
        let endPointY: CGFloat =  rect.size.height
        let path = CGMutablePath()
        path.move(to: CGPoint(x: startPointX, y: staerPointY))
        path.addLine(to: CGPoint(x: endPointX, y: endPointY))
        context.addPath(path)
        
        context.setStrokeColor(UIColor.init(hexColor: "FF8E00").cgColor)
        context.setLineWidth(1)
        /*
         phase參數表示在第一個虛線繪制的時候跳過多少個點
         lengths的值{10,10}表示先繪制10個點,再跳過10個點,如此反復
         如果把lengths值改為{10, 20, 10},則表示先繪制10個點,跳過20個點,繪制10個點,跳過10個點,再繪制20個點,如此反復
         */
        context.setLineDash(phase: 0, lengths: [5,5])
        context.strokePath()
        
        // 畫半圓
        UIColor.clear.set()
        /***設置圓心位置***/
        let circleY: CGFloat =  0
        let topCirclePoint: CGPoint = CGPoint(x: rect.size.width - 97, y: circleY)
        let bottomCenterPoint: CGPoint = CGPoint(x: rect.size.width - 97, y: rect.size.height)
        let topCircle = UIBezierPath(arcCenter: topCirclePoint, radius: 5, startAngle: -CGFloat.pi, endAngle: CGFloat.pi, clockwise: true)
        let bottpmCircle = UIBezierPath(arcCenter: bottomCenterPoint, radius: 5, startAngle: -CGFloat.pi, endAngle: CGFloat.pi, clockwise: true)
        context.setBlendMode(.clear)
        context.addPath(topCircle.cgPath)
        context.addPath(bottpmCircle.cgPath)
        context.fillPath()
    }

}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM