gpt4 book ai didi

ios - 使用UIBezierPath在2点之间绘制波浪

转载 作者:行者123 更新时间:2023-12-01 16:13:58 26 4
gpt4 key购买 nike

我正在尝试给UITableViewCell一个“波浪形”底部,使其看起来像一个“撕纸”效果(用于订单收据)。
我想在单元的整个长度上绘制它。

我在StackOverflow上找到了this解决方案,该解决方案在两点之间创建了一个正弦。

我尝试更改该代码以达到所需的效果(我知道我的代码有很多错误):

    let path = UIBezierPath()
let origin = CGPoint(x: 0, y: bounds.size.height / 2)
path.move(to: origin)

let graphWidth: CGFloat = 0.8 // Graph is 80% of the width of the view
let amplitude: CGFloat = 0.5 // Amplitude of sine wave is 30% of view

for angle in stride(from: 1.0, through: bounds.size.width * 5.0, by: 1.0) {
let x = origin.x + CGFloat(angle/360.0) * bounds.size.width * (360 / (bounds.size.width * 10.0))
let y = origin.y - CGFloat(sin(angle/180.0 * CGFloat.pi)) * bounds.size.height * amplitude * (360 / (bounds.size.width * 10.0))
path.addLine(to: CGPoint(x: x, y: y))
}

我想要达到的是:
wave

最好的方法是什么?如果我能获得解决方案之上的工作并且看起来像图像,那将是完美的。如果有人有其他建议,我愿意接受所有建议。

最佳答案

全部归功于vacawama answer。您可以如下实现

class SineView: UIView {
let graphWidth: CGFloat = 0.15
let amplitude: CGFloat = 0.1

override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height

let origin = CGPoint(x: 0, y: height * 0.50)

let path = UIBezierPath()
path.move(to: origin)

var endY: CGFloat = 0.0
let step = 5.0
for angle in stride(from: step, through: Double(width) * (step * step), by: step) {
let x = origin.x + CGFloat(angle/360.0) * width * graphWidth
let y = origin.y - CGFloat(sin(angle/180.0 * Double.pi)) * height * amplitude
path.addLine(to: CGPoint(x: x, y: y))
endY = y
}
path.addLine(to: CGPoint(x: width, y: endY))
path.addLine(to: CGPoint(x: width, y: height))
path.addLine(to: CGPoint(x: 0, y: height))
path.addLine(to: CGPoint(x: 0, y: origin.y))

UIColor.black.setFill()
path.fill()
UIColor.black.setStroke()
path.stroke()
}
}

用法
class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()

let size = view.frame.size
let sineView = SineView(frame: CGRect(x: 0, y: 100, width: size.width, height: 60))
sineView.backgroundColor = .white
self.view.addSubview(sineView)
}
}

输出

enter image description here

您可以使用 graphWidthamplitude随意调整图表。

关于ios - 使用UIBezierPath在2点之间绘制波浪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54135236/

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