2017-08-02 81 views
0

我得为我的视图中创建一个面具布局UIView的遮罩层,但我不能让我想获得创建使用CAShapeLayer()

@IBOutlet weak var viewToCrop: UIView! 
let angle = CGFloat(2*M_PI/3) 

func createMask() { 
    let mask = CAShapeLayer() 
    mask.frame = viewToCrop.layer.bounds 
    let heightButton = viewToCrop.frame.height 
    let lineWidth = -heightButton/tan(angle) 

    let width = viewToCrop.layer.frame.size.width 
    let height = viewToCrop.layer.frame.size.height 

    let path = CGPathCreateMutable() 
    CGPathMoveToPoint(path, nil, 0, 0) 
    CGPathAddLineToPoint(path, nil, width, 0) 
    CGPathMoveToPoint(path, nil, width - lineWidth, height) 
    CGPathAddLineToPoint(path, nil, lineWidth, height) 
    CGPathAddLineToPoint(path, nil, 0, 0) 

    mask.path = path 
    viewToCrop.layer.mask = mask 
} 

我需要建立这样的数字结果:

enter image description here

但是运行代码后,我得到的矩形。 我在做什么错?

P.S.我工作的一个传统项目上斯威夫特2

+0

什么价值角度在这里? – agibson007

+0

60度@ agibson007 –

+0

也是为什么斯威夫特2? – agibson007

回答

1

我没有斯威夫特2编译器选项,但我要带刺,希望得到您关闭。我认为最重要的是路径lineWidth需要被坐标除以2。另外要注意的是,如果视图的高度太大,那么60太陡。我会建议根据百分比绘制它,除非你需要确切的角度。如果没有Swift 2编译器,我会尽我所能让我知道。

@IBOutlet weak var viewToCrop: UIView! 
let angle = CGFloat(2*M_PI/3) 

func createMask() { 
    let mask = CAShapeLayer() 
    mask.frame = viewToCrop.layer.bounds 
    let heightButton = viewToCrop.frame.width 
    let lineWidth = -heightButton/tan(angle) 

    let width = viewToCrop.layer.frame.size.width 
    let height = viewToCrop.layer.frame.size.height 

    let path = CGPathCreateMutable() 
    CGPathMoveToPoint(path, nil, 0, 0) 
    CGPathAddLineToPoint(path, nil, width, 0) 
    CGPathMoveToPoint(path, nil, width - lineWidth/2, height) 
    CGPathAddLineToPoint(path, nil, lineWidth/2, height) 
    CGPathAddLineToPoint(path, nil, 0, 0) 

    mask.path = path 
    viewToCrop.layer.mask = mask 
    } 

结果 Result