美文网首页
圆柱体View

圆柱体View

作者: 奋斗的遗忘人 | 来源:发表于2024-07-11 11:38 被阅读0次
BE91DF80-7766-41C4-B0AC-B5DC47D24EAF.png
class CylinderView: UIView {
    
    // 使用统一颜色
    //3C83EA
    var cylinderColor: UIColor = UIColor(hexString: "#3C83EA")
    
    //3B89E3
    var cylinderTopColor: UIColor = UIColor(hexString: "#3B89E3")
    var cylinderHeight: CGFloat = 0 {
        didSet {
            // 当 cylinderHeight 改变时,重新绘制视图
            setNeedsDisplay()
        }
    }

    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }

        // 设置基本参数
        let width = rect.width
        let height = rect.height
        // 限制 cylinderHeight 的最小值为 30
        let clampedCylinderHeight = max(cylinderHeight, 30)

        // 计算圆柱体的上椭圆和下椭圆的位置
        let topEllipseRect = CGRect(x: rect.minX, y: height - clampedCylinderHeight, width: width, height: 30)
        
        let bottomEllipseRect = CGRect(x: rect.minX, y: height - 30, width: width, height: 30)

        // 计算圆柱体的侧面位置
        let sideHeight = clampedCylinderHeight - 30
        let sideRect = CGRect(x: rect.minX, y: height - clampedCylinderHeight + 15, width: width, height: sideHeight)

        // 清除之前的内容
        context.clear(rect)

        // 画圆柱体的侧面
        context.addRect(sideRect)
        context.setFillColor(cylinderColor.cgColor)
        context.fillPath()

        // 画下椭圆
        context.saveGState()
        context.addEllipse(in: bottomEllipseRect)
        context.setFillColor(cylinderColor.cgColor)
        context.fillPath()
        context.restoreGState()
        
        // 画上椭圆
        context.saveGState()
        let topEllipsePath = UIBezierPath(ovalIn: topEllipseRect)
        context.setFillColor(cylinderTopColor.cgColor)
        context.addPath(topEllipsePath.cgPath)
        context.fillPath()
        context.restoreGState()

        // 添加顶部椭圆的渐变效果以增强立体感
        let gradientColors = [cylinderTopColor.withAlphaComponent(0.5).cgColor, cylinderTopColor.withAlphaComponent(1.0).cgColor]
        let gradient = CGGradient(colorsSpace: CGColorSpaceCreateDeviceRGB(), colors: gradientColors as CFArray, locations: [0.0, 1.0])!

        context.saveGState()
        context.addEllipse(in: topEllipseRect)
        context.clip()
        context.drawLinearGradient(gradient, start: CGPoint(x: rect.midX, y: rect.minY), end: CGPoint(x: rect.midX, y: rect.minY + clampedCylinderHeight), options: [])
        context.restoreGState()
    }
}

使用方法

//因为最小值为30
self.waitView.cylinderHeight = 30 + (self.waitView.m_height-30) * (noNumber / allNumber)

相关文章

网友评论

      本文标题:圆柱体View

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