swift - 画图 - 画矩形,虚线,圆和半圆

swift - 画图 - 画矩形,虚线,圆和半圆_第1张图片

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()

    }


}

你可能感兴趣的:(swift - 画图 - 画矩形,虚线,圆和半圆)