ios - UIBezierPath 和 CAShapeLayer

标签 ios swift uibezierpath cashapelayer

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

问题是左角是正确的圆角,而右角不是,我不明白为什么会发生这种情况,我做错了什么。

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

当前结果图像 Current result image

所需的结果图像 required result image .

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:) for UIBezierPath

更多信息请参见 Apple documentation

使用示例位于此处:

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/

相关文章:

ios - 无法检索 Shoutcast .pls 流

ios - 如何重新计算 NSFetchedResultsController 的 IndexPath,记录分为 3 个部分 : today, future ,过去?

swift - 如何通过 editActionsForRowAt 将数据传递给 Viewcontroller?

ios - 隐藏通过 NotificationService Extension 收到的通知

ios - 将我的渐变设置为 BezierPath 的弧线

ios - 无法将属性连接到 Storyboard

java - Android(或 iOS)——图片上传队列

objective-c - 使用 Json 在 Objective C 中发布数据

ios - 在 CGPath 或 UIBezierPath 内播放视频

Swift - 如何使动画箭头指向正确的方向?