简体   繁体   English

类钻石UIView

[英]Diamond-like UIView

I am trying to create a UIView with corners like a shape of a diamond, as shown in the picture: 我正在尝试创建一个带有菱形的角的UIView,如图所示:

钻石

I am familiar with rounding off corners: 我熟悉四舍五入的方法:

myView.layer.cornerRadius = 10

However, I want a different shape. 但是,我想要一个不同的形状。 How could I create this effect? 我怎样才能产生这种效果? Thanks for your help! 谢谢你的帮助!

Best way to solve a problem like this is by using CAShapeLayer. 解决此类问题的最佳方法是使用CAShapeLayer。 Here's the kind of thing that would work: paste it into a playground and see how it clips off the corners. 这是可行的方法:将其粘贴到操场上,看看它如何修剪掉角落。

import UIKit
import XCPlayground

extension UIView {
    func maskCorners(inset: CGFloat) {
        let path = UIBezierPath()
        path.moveToPoint(CGPoint(x: bounds.origin.x + inset,y: 0))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds) - inset,y: 0))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds), y: bounds.origin.y + inset))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds), y: CGRectGetMaxY(bounds) - inset))
        path.addLineToPoint(CGPoint(x: CGRectGetMaxX(bounds) - inset,y: CGRectGetMaxY(bounds)))
        path.addLineToPoint(CGPoint(x: bounds.origin.x + inset,y: CGRectGetMaxY(bounds)))
        path.addLineToPoint(CGPoint(x: 0,y: CGRectGetMaxY(bounds) - inset))
        path.addLineToPoint(CGPoint(x: 0,y: bounds.origin.y + inset))
        path.addLineToPoint(CGPoint(x: bounds.origin.x + inset,y: 0))

        let mask = CAShapeLayer()
        mask.frame = bounds
        mask.path = path.CGPath
        layer.mask = mask
    }
}

let diamond = UIView(frame: CGRect(x:0, y: 0, width: 100, height:100))
diamond.backgroundColor = UIColor.redColor()
XCPlaygroundPage.currentPage.liveView = diamond
diamond.maskCorners(25)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM