ios - 如何在 SWIFT 中绘制自定义圆角矩形?

标签 ios swift core-graphics uibezierpath

I'm trying to draw this shape

setting cornerRadius doesn't work

我正在尝试以编程方式绘制上图所示的形状。

这个形状有自定义的圆角。

view.layer.cornerRadius = some value less than half diameter

这没有用。设置 cornerRadius 在每一侧绘制直线(如底部图像所示),但我尝试绘制的形状根本没有直线,它不是椭圆形。

我也试过下面没有运气。这段代码只是画了一个椭圆。

var path = UIBezierPath(ovalIn: CGRect(x: 000, y: 000, width: 000, height: 000))

我相信这不能通过设置 cornerRadius 来完成。

应该还有更多的东西。

我不知道应该使用哪个类以及如何使用。

请任何人给我一些指导。

谢谢!

最佳答案

我通过绘制二次方程来实现这一点。

let dimention: CGFloat = some value

let path = UIBezierPath()
    path.move(to: CGPoint(x: dimension/2, y: 0))
    path.addQuadCurve(to: CGPoint(x: dimension, y: dimension/2),
                      controlPoint: CGPoint(x: dimension, y: 0))
    path.addQuadCurve(to: CGPoint(x: dimension/2, y: dimension),
                      controlPoint: CGPoint(x: dimension, y: dimension))
    path.addQuadCurve(to: CGPoint(x: 0, y: dimension/2),
                      controlPoint: CGPoint(x: 0, y: dimension))
    path.addQuadCurve(to: CGPoint(x: dimension/2, y: 0),
                      controlPoint: CGPoint(x: 0, y: 0))
    path.close()

    let shapeLayer = CAShapeLayer()
    shapeLayer.path = path.cgPath
    shapeLayer.strokeColor = UIColor.blue.cgColor
    shapeLayer.fillColor = UIColor.clear.cgColor
    shapeLayer.lineWidth = 1.0
    shapeLayer.position = CGPoint(x: 0, y: 0)

    self.someView.layer.addSublayer(shapeLayer)

关于ios - 如何在 SWIFT 中绘制自定义圆角矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57265232/

相关文章:

ios - 使用 startMonitoringVisits 监控区域

ios - 将数据从 Swift View Controller 传递到 Objective-C View Controller

c - 如何快速捕获无效的枚举

cocoa - 核心显卡0x1​​04567911

ios - UIButton 函数添加点击样式

ios - 无法在 iPod Touch 中部署 Xamarin 项目

bash - 带有默认值和killall bash命令的NSTask

ios - 更改 UIKit 和/或 CoreGraphics 中的坐标系

objective-c - Objective-C 中框架的水平翻转

ios - UIWebview:不旋转也不调整大小以适应整个屏幕