【发布时间】:2020-03-20 16:28:36
【问题描述】:
我正在尝试更改我在本教程中创建的 UIBezierPath 的形状: [https://www.appcoda.com/bezier-paths-introduction/] 这是我的代码:
class Geometry: UIView {
//var path: UIBezierPath!
var path = UIBezierPath()
override func draw(_ rect: CGRect) {
createLine(x: 100, y: 100)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func transformShape(x:CGFloat, y:CGFloat)
{
path.removeAllPoints()
createLine(x: x, y: y)
}
func createLine(x: CGFloat, y: CGFloat)
{
var path = UIBezierPath()
path.move(to: CGPoint(x: 0.0, y: 0.0))
path.addLine(to: CGPoint(x: x, y: y))
path.close()
path.fill()
path.stroke()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch = touches.first
let location = (touch?.location(in: self))!;
transformShape(x:location.x, y:location.y)
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch = touches.first
let location = (touch?.location(in: self))!;
transformShape(x:location.x, y:location.y)
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?)
{
let touch = touches.first
let location = (touch?.location(in: self))!;
transformShape(x:location.x, y:location.y)
}
}
我已经像这样在视图控制器中添加了视图:
import UIKit
var geo = Geometry()
let screenWidth: Int = 1024
let screenHeight: Int = 768
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
geo = Geometry(frame: CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight))
self.view.addSubview(geo)
}
}
为了更容易理解我想做什么,我做了这个。我希望能够在不改变 y 位置的情况下将两条线的末端在 x 上左右移动
除了动画,我没有找到任何东西。但这不是我想要完成的。三角形的顶部应该跟随手指的运动。谢谢
【问题讨论】:
-
很简单:随着手指的移动,重新绘制路径,
addLine(to: CGPoint(x: x, y: y))线变为手指现在所在的位置。 -
@matt 当我这样做时,我收到此错误:[未知进程名称] CGContextSetFillColorWithColor:无效上下文 0x0。如果要查看回溯,请设置 CG_CONTEXT_SHOW_BACKTRACE 环境变量。
-
我很确定我应该在重新添加之前删除该行。但是我得到了同样的错误
标签: ios swift uibezierpath uitouch