Diamond-like UIView

风流意气都作罢 提交于 2019-12-25 06:56:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!