swift - 通过拖动 View 边缘来变换 View (Swift)

标签 swift drawing

我尝试制作一个应用程序,用户可以在其中绘制或添加箭头,并转换该箭头(平移、旋转等)。 目前,我设法绘制箭头并对其进行所有转换,但我现在想做的是能够通过拖动其边缘来修改箭头。

为了绘制箭头,我只需创建一个高度为 20px(箭头的粗细)、宽度为 400(箭头的长度)的 UIView。

func drawArrow(frame: CGRect) {
    let thicknessArrow = 20
    let viewHorizontalArrow = UIView()
    viewHorizontalArrow.frame.origin = CGPoint(x: 100, y: 600)
    viewHorizontalArrow.frame.size = CGSize(width: 400, height: thicknessArrow)

    drawDoubleArrow(viewHorizontalArrow, startPoint: CGPoint(x: 0, y: thicknessViewWithArrow/2), endPoint: CGPoint(x: viewHorizontalArrow.frame.width, y: thicknessViewWithArrow/2), lineWidth: 10, color: UIColor.blackColor())

}

之后,我通过平移、捏合和旋转手势来变换 UIView。

函数“drawDoubleArrow”使用BezierPath创建一个箭头并将其添加到UIView的图层中。

我希望这些解释足够清楚:)。

你能帮我找到解决方案吗?

谢谢!

最佳答案

UIBezierPath 本身无法轻松地通过手势进行操作,因为它无法识别手势。但是 UIView 可以识别手势。结合 CALayer 的转换能力及其 hitTest() 方法,我认为您可以实现您想要的。

// I'm declaring the layer as a shape layer, but depending on how your error thick is, you may need a rectangular one
let panGesture = UIPanGestureRecognizer()
var myLayer = CAShapeLayer()

viewDidLoad:

// I'm assuming you've created myBezierPath, an arrow path
myLayer.path = myBezierPath.cgPath

// Adding the pan gesture to the view's controller
panGesture.addTarget(self, action: #selector(moveLayer))
self.addGestureRecognizer(panGesture)

移动层:

func moveLayer(_ recognizer:UIPanGestureRecognizer) {
    let p = recognizer.location(in: self)

    // You will want to loop through all the layers you wish to transform
    if myLayer.hitTest(p) != nil {
        myLayer.position = p
    }
}

关于swift - 通过拖动 View 边缘来变换 View (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42276507/

相关文章:

twitter-bootstrap - 如何允许访问者使用 Bootstrap 在图表上放置标记?

ios - 来自 web 服务的更新表中的 viewWillAppear 延迟

Swift 将泛型转换为带有 nil 值的可选会导致 fatalError

ios - UIColor:灰度值是一个属性吗?

swift - tvOS 检查当前聚焦的 ui 元素是否是 CollectionViewCell

ios - GL图纸 View 在旋转时清除图纸

python - 如何在 Python 中将 SVG 路径插入像素坐标(不仅仅是光栅)

Android - 在不同设备上绘图

objective-c - 使用 Storyboard在 Xcode 6 os x 应用程序中更改不同的 View

macos - 如何在 CTFrameRef 中每行仅绘制 8 个字符?