代码之家  ›  专栏  ›  技术社区  ›  Ali

Swift 4-创建2种背景色的UIView

  •  1
  • Ali  · 技术社区  · 6 年前

    我有一个和它的超级视图一样宽/高的UIView。这就是我想要的。

    enter image description here

    目前我使用的是静态背景图像。有什么想法吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Sahil Manchanda    6 年前

    结果

    Result

    代码

    import UIKit
    @IBDesignable
    public class AngleView: UIView {
    
        @IBInspectable public var fillColor: UIColor = .blue { didSet { setNeedsLayout() } }
    
        var points: [CGPoint] = [
            .zero,
            CGPoint(x: 1, y: 0),
            CGPoint(x: 1, y: 0.4),
            CGPoint(x: 0, y: 0.5)
            ] { didSet { setNeedsLayout() } }
    
        private lazy var shapeLayer: CAShapeLayer = {
            let _shapeLayer = CAShapeLayer()
            self.layer.insertSublayer(_shapeLayer, at: 0)
            return _shapeLayer
        }()
    
        override public func layoutSubviews() {
            shapeLayer.fillColor = fillColor.cgColor
    
            guard points.count > 2 else {
                shapeLayer.path = nil
                return
            }
    
            let path = UIBezierPath()
    
            path.move(to: convert(relativePoint: points[0]))
            for point in points.dropFirst() {
                path.addLine(to: convert(relativePoint: point))
            }
            path.close()
    
            shapeLayer.path = path.cgPath
        }
    
        private func convert(relativePoint point: CGPoint) -> CGPoint {
            return CGPoint(x: point.x * bounds.width + bounds.origin.x, y: point.y * bounds.height + bounds.origin.y)
        }
    }
    

    Source 刚刚修改了值:D

        2
  •  2
  •   MhmdRizk    6 年前

    enter image description here

    swift 4:你可以在你的视图中添加子层,而不是创建一个有多种背景色的视图。

    //connect your view.
    
    @IBOutlet weak var yourView: UIView!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        //add a shape 
        let shape = CAShapeLayer()
        self.yourView.layer.addSublayer(shape)
        shape.strokeColor = UIColor.black.cgColor
        shape.fillColor = UIColor.black.cgColor
    
        // add your path 
        // you can simply adjust the points.
        let path = UIBezierPath()
        path.move(to: CGPoint(x: 0, y: 0))
        path.addLine(to: CGPoint(x: 0, y: (3*yourView.bounds.height)/4))
        path.addLine(to: CGPoint(x:self.yourView.bounds.width , y: yourView.bounds.height/2))
        path.addLine(to: CGPoint(x: self.yourView.bounds.width, y: 0))
        path.close()
        shape.path = path.cgPath
    
    }