Swift从用户点击添加图像到UIImageView

时间:2021-10-29 08:23:57

I have a ScrollView with an ImageView inside. Here a user can select a point on the image and it will print out the coordinates.

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

I'm also trying to add an image ("pin") to the tapped coordinate but am unsure how to...

我也试图将图像(“pin”)添加到tapped坐标但不确定如何...

// 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)")

}

1 个解决方案

#1


1  

In your tapAction:

在你的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)

So what I´m doing is adding a new UIImageView with the x and y from touchPoint.x and touchPoint.y into your current sharkImage.

所以我正在做的是添加一个新的UIImageView,其中x和y从touchPoint.x和touchPoint.y到你当前的sharkImage。

#1


1  

In your tapAction:

在你的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)

So what I´m doing is adding a new UIImageView with the x and y from touchPoint.x and touchPoint.y into your current sharkImage.

所以我正在做的是添加一个新的UIImageView,其中x和y从touchPoint.x和touchPoint.y到你当前的sharkImage。