簡體   English   中英

帶有角半徑的漸變UIButton邊框

[英]Gradient UIButton's border with corner radius

我編寫了該代碼,該代碼可在iPhone X上使用,但不適用於iPhone SE。 這就是我們在iPhone SE上擁有的

有任何人知道為什么它可以在iPhone X上正確運行而不能在iPhone SE上運行

我在viewDidLayoutSubviews()中調用此函數

extension UIView {
    enum Direction {
        case horizontal
        case vertical
    }

    func addGradient(cornerRadius: CGFloat, colors: [UIColor], lineWidth: CGFloat, direction: Direction) {
       self.layer.cornerRadius = cornerRadius
        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.colors = colors.map({ (color) -> CGColor in
            color.cgColor
        })

        switch direction {
        case .horizontal:
            gradient.startPoint = CGPoint(x: 0, y: 1)
            gradient.endPoint = CGPoint(x: 1, y: 1)
        case .vertical:
            gradient.startPoint = CGPoint(x: 0, y: 0)
            gradient.endPoint = CGPoint(x: 0, y: 1)
        }

        var shadowLayer: CAShapeLayer!
        shadowLayer = CAShapeLayer()
        shadowLayer.lineWidth = lineWidth
        shadowLayer.path = UIBezierPath(roundedRect: self.bounds.insetBy(dx: lineWidth, dy: lineWidth), cornerRadius: cornerRadius).cgPath
        shadowLayer.fillColor = nil
        shadowLayer.strokeColor = UIColor.black.cgColor
        gradient.mask = shadowLayer
        self.layer.addSublayer(gradient)
    }
}

由於多次調用viewDidLayoutSubviews ,因此必須確保僅創建一次漸變圖層。 添加這樣的支票:

func addGradient(cornerRadius: CGFloat, colors: [UIColor], lineWidth: CGFloat, direction: Direction) {
    self.layer.cornerRadius = cornerRadius

    if let gradient = self.layer.sublayers?.last as? CAGradientLayer {
        // gradient layer already exists - update its frame
        gradient.frame = bounds
    } else {
        // gradient layer does not exist yet - create it
        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.colors = colors.map({ (color) -> CGColor in
            color.cgColor
        })

        switch direction {
        case .horizontal:
            gradient.startPoint = CGPoint(x: 0, y: 1)
            gradient.endPoint = CGPoint(x: 1, y: 1)
        case .vertical:
            gradient.startPoint = CGPoint(x: 0, y: 0)
            gradient.endPoint = CGPoint(x: 0, y: 1)
        }

        var shadowLayer: CAShapeLayer!
        shadowLayer = CAShapeLayer()
        let rectPath = UIBezierPath(roundedRect: self.bounds.insetBy(dx: lineWidth, dy: lineWidth), cornerRadius: cornerRadius).cgPath
        shadowLayer.path = rectPath
        shadowLayer.lineWidth = lineWidth
        shadowLayer.fillColor = nil
        shadowLayer.strokeColor = UIColor.black.cgColor
        gradient.mask = shadowLayer
        self.layer.addSublayer(gradient)
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM