gpt4 book ai didi

ios - 使用 UIBezierPath 绘制圆角

转载 作者:搜寻专家 更新时间:2023-11-01 05:50:00 25 4
gpt4 key购买 nike

我有一个设计元素很难弄清楚;希望有人能指出我正确的方向。我要构建的元素是这样的;

Rounded Button With No Bottom Border

实际上,它是一个圆角矩形,在左侧、顶部和右侧都有一个描边(底部应该没有描边)。

我已经尝试使用以下代码;

// Create the rounded rectangle
let maskPath = UIBezierPath(roundedRect: myView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 4.0, height: 4.0))

// Setup a shape layer
let shape = CAShapeLayer()

// Create the shape path
shape.path = maskPath.cgPath

// Apply the mask
myView.layer.mask = shape

随后,我使用以下方法在矩形周围绘制笔划;

// Add border
let borderLayer = CAShapeLayer()
borderLayer.path = maskPath.cgPath
borderLayer.fillColor = UIColor.clear.cgColor
borderLayer.strokeColor = UIColor.white.cgColor
borderLayer.lineWidth = 2.0
borderLayer.frame = self.bounds
self.layer.addSublayer(borderLayer)

这会产生下图;

Rounded Rect with Stroke

我一直无法弄清楚如何删除底部笔画使用 UIBezierPath() 绘制项目,但以某种方式将角变圆这将与圆角矩形相同(我在同一 View 中出于不同目的使用另一个圆角矩形,并且圆角需要相同)。

谢谢!

最佳答案

CGMutablePath 方法 addArc(tangent1End:tangent2End:radius:transform:) 旨在轻松制作圆角。

extension CGMutablePath {
static func bottomlessRoundedRect(in rect: CGRect, radius: CGFloat) -> CGMutablePath {
let path = CGMutablePath()
path.move(to: CGPoint(x: rect.minX, y: rect.maxY))
path.addArc(tangent1End: CGPoint(x: rect.minX, y: rect.minY), tangent2End: CGPoint(x: rect.maxX, y: rect.minY), radius: radius)
path.addArc(tangent1End: CGPoint(x: rect.maxX, y: rect.minY), tangent2End: CGPoint(x: rect.maxX, y: rect.maxY), radius: radius)
path.addLine(to: CGPoint(x: rect.maxX, y: rect.maxY))
return path
}
}

一旦你有了那个方法,最好使用自定义 View 来管理 CAShapeLayer,这样它就可以自动适应大小的变化。演示:

class MyFrameView: UIView {
override class var layerClass: AnyClass { return CAShapeLayer.self }

override func layoutSubviews() {
super.layoutSubviews()
let layer = self.layer as! CAShapeLayer
layer.lineWidth = 2
layer.strokeColor = UIColor.white.cgColor
layer.fillColor = nil
layer.path = CGMutablePath.bottomlessRoundedRect(in: bounds.insetBy(dx: 10, dy: 10), radius: 8)
}
}

import PlaygroundSupport

let view = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 60))
view.backgroundColor = #colorLiteral(red: 0.7034167647, green: 0.4845994711, blue: 0.6114708185, alpha: 1)
let frameView = MyFrameView(frame: view.bounds)
frameView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.addSubview(frameView)
let label = UILabel(frame: view.bounds)
label.text = "Hello"
label.textColor = .white
label.textAlignment = .center
view.addSubview(label)

PlaygroundPage.current.liveView = view

结果:

demo

关于ios - 使用 UIBezierPath 绘制圆角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43439854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com