UIBezierPath和CAShapeLayer

UIBezierPath和CAShapeLayer

我想要一个带有圆角的矩形。为此,我使用UIBezierPathCAShapeLayer

问题是左角正确舍入,而右角不是正确,而且我不明白为什么会这样,这是我做错了。

对我来说,使当前代码有效是很重要的,不幸的是,通过cornerRadius或其他方式解决问题对我而言并不感兴趣。

当前结果图像
 



所需结果图片


import UIKit

func getRadians(from degrees: CGFloat) -> CGFloat {
    return degrees * CGFloat.pi / 180
}

let view = UIView()
view.backgroundColor = .green

let width: CGFloat = 800
let height: CGFloat = 400

view.frame = CGRect(x: 0, y: 0, width: width, height: height)

let cornersRadius: CGFloat = 100
var path = UIBezierPath()

path.move(to: CGPoint(x: 0, y: 0))

path.addLine(to: CGPoint(x: width, y: 0))
path.addLine(to: CGPoint(x: width, y: height))

path.addLine(to: CGPoint(x: 0, y: height))
path.addLine(to: CGPoint(x: 0, y: 0))

path = path.reversing()

let topLeft = UIBezierPath()
topLeft.move(to: CGPoint(x: 0, y: cornersRadius))

topLeft.addLine(to: CGPoint(x: 0, y: 0))
topLeft.addLine(to: CGPoint(x: cornersRadius, y: 0))

topLeft.addArc(withCenter: CGPoint(x: cornersRadius, y: cornersRadius), radius: cornersRadius, startAngle: getRadians(from: 270), endAngle: getRadians(from: 180), clockwise: false)
topLeft

let topRight = UIBezierPath()
topRight.move(to: CGPoint(x: width, y: cornersRadius))

topRight.addLine(to: CGPoint(x: width, y: 0))
topRight.addLine(to: CGPoint(x: width - cornersRadius, y: 0))

topRight.addArc(withCenter: CGPoint(x: width - cornersRadius, y: cornersRadius), radius: cornersRadius, startAngle: getRadians(from: 270), endAngle: getRadians(from: 0), clockwise: true)
topRight

path.append(topLeft)
path.append(topRight)

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

view.layer.mask = layer
view

最佳答案

有一种更简单的方法可以实现它。您可以使用以下方法:

init(roundedRect:byRoundingCorners:cornerRadii:)表示UIBezierPath

Apple documentation中的更多信息

使用示例ls在这里:

let cornerRadius = CGFloat(10.0)
let roundedCorners = roundedCorners.union([.topLeft, .topRight])

let path = UIBezierPath(roundedRect:maskRect, byRoundingCorners:roundedCorners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius))

let maskLayer = CAShapeLayer()
maskLayer.frame = YOUR_VIEW_TO_MASK.bounds
maskLayer.path = maskPath.cgPath

YOUR_VIEW_TO_MASK.layer.mask = maskLayer

关于ios - UIBezierPath和CAShapeLayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53079266/

10-11 19:55