use Core Graphics to draw

drawLines

func drawLines() {
        guard let ctx = UIGraphicsGetCurrentContext() else {
            return
        }
        ctx.beginPath()
        ctx.move(to: CGPoint(x: 20, y: 20))
        ctx.addLine(to: CGPoint(x: 250, y: 100))
        ctx.addLine(to: CGPoint(x: 100, y: 200))
        ctx.setLineWidth(5)
        ctx.closePath()
        ctx.strokePath()
    }

drawRectangle

func drawRectangle() {
        let center = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
        let rectangleWidth: CGFloat = 100
        let rectangleHeight: CGFloat = 100
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.addRect(CGRect(x: center.x - (0.5 * rectangleWidth), y: center.y - (0.5 * rectangleHeight), width: rectangleWidth, height: rectangleHeight))
        ctx.setLineWidth(10)
        ctx.setStrokeColor(UIColor.gray.cgColor)
        ctx.strokePath()
        ctx.setFillColor(UIColor.green.cgColor)
        ctx.addRect(CGRect(x: center.x - (0.5 * rectangleWidth), y: center.y - (0.5 * rectangleHeight), width: rectangleWidth, height: rectangleHeight))
        ctx.fillPath()
    }

drawCircle

func drawCircle() {
        let center = CGPoint(x: self.frame.size.width / 2, y: self.frame.size.height / 2)
        guard let ctx = UIGraphicsGetCurrentContext() else { return }
        ctx.beginPath()
        ctx.setLineWidth(5)
        let x: CGFloat = center.x
        let y: CGFloat = center.y
        let radius: CGFloat = 100
        let endAngle: CGFloat = CGFloat(2 * M_PI)
        ctx.addArc(center: CGPoint(x: x,y: y), radius: radius, startAngle: 0, endAngle: endAngle, clockwise: true)
        ctx.strokePath()
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容