问题
I am trying to create a UIView with corners like a shape of a diamond, as shown in the picture:
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!
回答1:
Best way to solve a problem like this is by using 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)
来源:https://stackoverflow.com/questions/36803227/diamond-like-uiview