ios - 从用户点击快速将图像添加到 UIImageView

标签 ios swift uiscrollview uiimageview uitapgesturerecognizer

我有一个 ScrollView,里面有一个 ImageView。 在这里,用户可以在图像上选择一个点,它会打印出坐标。

我也在尝试将图像(“图钉”)添加到点击的坐标,但不确定如何...

// MARK: - Outlets
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var sharkImage: UIImageView!

// MARK: - View Did Load
override func viewDidLoad() {
    super.viewDidLoad()

    scrollView.minimumZoomScale = 1.0
    scrollView.maximumZoomScale = 6.0

    scrollView.delegate = self

    let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapAction))

    self.sharkImage.isUserInteractionEnabled = true
    self.sharkImage.addGestureRecognizer(tapGestureRecognizer)
}

// MARK: - Scroll View
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
    return sharkImage
}

// MARK: - Functions
func tapAction(sender: UITapGestureRecognizer) {
    // Get points for the UIImageView
    let touchPoint = sender.location(in: self.sharkImage)
    print(touchPoint)

    // Get points from the image itself
    let z1 = touchPoint.x * (sharkImage.image?.size.width)! / sharkImage.frame.width
    let z2 = touchPoint.y * (sharkImage.image?.size.height)! / sharkImage.frame.height
    print("Touched point (\(z1), \(z2)")

}

最佳答案

在你的tapAction中:

let pin = UIImageView(frame: CGRect(x: touchPoint.x - 20, y: touchPoint.y - 20, width: 40, height: 40))
pin.image = UIImage(named: "pin")
sharkImage.addSubview(pin)

所以我正在做的是添加一个新的 UIImageView 以及来自 touchPoint.xxy > 和 touchPoint.y 到您当前的 sharkImage

关于ios - 从用户点击快速将图像添加到 UIImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44471242/

相关文章:

ios - 恢复ViewController状态的最佳方法是什么

ios - 如何更改 XCTest for iOS 测试的方向?

ios - 只能选择一个联系人,如何使用ContactUI进行多选?

ios - 我已使用桥接 header 将 Objective-C 文件导入到 Swift 项目中,但出现错误 "Expected a type"

ios - UIScrollView:没有任何内容滚动

ios - 具有动态大小内容的 UIScrollView

ios - UIScrollView 添加顶部空白

ios - 如何使用自动布局根据其 subview 调整父 View 的高度

iphone - iOS 应用错误 : I screwed up somewhere in date calculation

ios - 类型 "Patient"没有下标成员