美文网首页
[Swift] 绘图

[Swift] 绘图

作者: 巨馍蘸酱 | 来源:发表于2022-07-20 11:50 被阅读0次

    iOS 绘图

    • 自定义 UIView 类,重写 draw() 方法并调用 UIBezierPath 类相关方法
    • 自定义 UIView 类,重写 draw() 方法并调用 UIGraphicsGetCurrentContext 类相关方法
    • UIBezierPath 类与 CAShaperLayer 类搭配

    draw + UIBezierPath

        override func draw(_ rect: CGRect) {
            super.draw(rect)
            
            print("=========== \(#function)")
            
    //        //设定颜色,并绘制它们
            UIColor.systemRed.setFill()
            UIColor.systemBlue.setStroke()
            
            //创建一个矩形,它的所有边都内缩5%
            let drawingRect = self.bounds.insetBy(dx: self.bounds.size.width * 0.05, dy: self.bounds.size.height * 0.05)
            
            //确定组成绘画的点 
            let rightMid = CGPoint(x: drawingRect.maxX, y: drawingRect.midY) 
            let leftMid = CGPoint(x: drawingRect.minX, y: drawingRect.midY)
    
            // 绘制水平线
            let lineBezierPath = UIBezierPath()
            lineBezierPath.move(to: leftMid)
            lineBezierPath.addLine(to: rightMid)
            lineBezierPath.lineWidth = 10
            lineBezierPath.stroke()
        }
    

    draw + UIGraphicsGetCurrentContext (CGContext)

        override func draw(_ rect: CGRect) {
            super.draw(rect)
            
            //获取绘图上下文
            guard let context = UIGraphicsGetCurrentContext() else {
                return
            }
            
            //创建一个矩形,它的所有边都内缩3
            let drawingRect = self.bounds.insetBy(dx: 3, dy: 3)
            
            //创建并设置路径
            let path = CGMutablePath()
            
            //圆弧半径
            let radius = min(drawingRect.width, drawingRect.height)/2
            //圆弧中点
            let center = CGPoint(x:drawingRect.midX, y:drawingRect.midY)
            //绘制圆弧
            path.addArc(center: center, radius: radius, startAngle: 0,
                        endAngle: CGFloat.pi * 1.5, clockwise: false)
            
            //添加路径到图形上下文
            context.addPath(path)
            
            //设置笔触颜色
            context.setStrokeColor(UIColor.orange.cgColor)
            //设置笔触宽度
            context.setLineWidth(6)
            
            //绘制路径
            context.strokePath()
        }
    

    UIBezierPath + CAShaperLayer

        /// 画圆角
        func roundCorners(_ corners: UIRectCorner, radius: CGFloat) {
            let maskPath = UIBezierPath(
                roundedRect: self.bounds,
                byRoundingCorners: corners,
                cornerRadii: CGSize(width: radius, height: radius)
            )
    
            let shape = CAShapeLayer()
            shape.path = maskPath.cgPath
            layer.mask = shape
        }
    

    鸣谢

    相关文章

      网友评论

          本文标题:[Swift] 绘图

          本文链接:https://www.haomeiwen.com/subject/nosdbrtx.html