【发布时间】:2018-10-31 20:40:24
【问题描述】:
我想得到一个上角圆角的矩形。为此,我使用UIBezierPath 和CAShapeLayer。
问题是左角是正确的,而右角不是,我不明白为什么会这样,我做错了什么。
使当前代码有效对我来说很重要,通过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
【问题讨论】:
-
bug 在这里:topRight.addLine(to: CGPoint(x: width, y: 0)) topRight.addLine(to: CGPoint(x: width - cornersRadius, y: 0))
-
我应该如何改变它?
-
使用单个 UIBezierPath 比尝试将路径添加在一起要容易得多。你在正确的道路上做错了什么是你实际上是在“填充”角落而不是移除它。
标签: ios swift uibezierpath cashapelayer