使用UIBezierPath向UIView添加阴影

问题描述 投票:0回答:1

我正在UIView的draw rect方法中创建自定义形状。它是一个箭头并且正在工作,但是我在添加阴影时遇到了麻烦。我尝试向“视图”本身和图层添加阴影,但是它不起作用。任何帮助将不胜感激。

import UIKit

class ArrowView: UIView {

    override func draw(_ rect: CGRect) {
        //Drawing Arrow
        let path = UIBezierPath()
        let edge:CGFloat = 20.0
        path.move(to: CGPoint(x: 0.0, y: 0.0))
        path.addLine(to: CGPoint(x: self.frame.width - edge, y: 0.0))
        path.addLine(to: CGPoint(x: self.frame.width , y: self.frame.height/2))
        path.addLine(to: CGPoint(x: self.frame.width - edge , y: self.frame.height))
        path.addLine(to: CGPoint(x: 0, y: self.frame.height))
        path.close()

        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask

    }
}

enter image description here

ios swift uiview uibezierpath
1个回答
0
投票

这里是获得暗影的方法

import UIKit

@IBDesignable
class ArrowView: UIView {


    private lazy var arrowLayer : CALayer = {
        let layer = CALayer()
        layer.backgroundColor = UIColor.red.cgColor
        return layer
    }()


    override init(frame: CGRect) {
        super.init(frame: frame)
        setupView()
    }

    required init?(coder: NSCoder) {
        super.init(coder: coder)

        setupView()


    }
    func setupView() {
        self.backgroundColor = .clear
        layer.shadowColor = UIColor.black.cgColor
        layer.shadowOpacity = 1
        layer.shadowOffset = .zero
        layer.shadowRadius = 10


        layer.addSublayer(arrowLayer)
    }

    private func updatePath() {
        let path = UIBezierPath()
        let edge:CGFloat = 20.0
        path.move(to: CGPoint(x: 0.0, y: 0.0))
        path.addLine(to: CGPoint(x: self.bounds.size.width - edge, y: 0.0))
        path.addLine(to: CGPoint(x: self.bounds.size.width , y: self.bounds.size.height/2))
        path.addLine(to: CGPoint(x: self.bounds.size.width - edge , y: self.bounds.size.height))
        path.addLine(to: CGPoint(x: 0, y: self.bounds.size.height))
        path.close()

        arrowLayer.frame = self.bounds

        let mask = CAShapeLayer()
        mask.path = path.cgPath

        arrowLayer.mask = mask
    }

    override func layoutSubviews() {
        updatePath()
    }

}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.