带有贴纸的 UIImageView 并在贴纸上添加手势

UIImageView with sticker and adding Gesture on Sticker

我有一个 ImageView 和上面的贴纸,现在我想在那个贴纸上添加手势,一切正常,但是,我的贴纸从 UIImageView 的图层中出来,如图所示。我只想在 ImageView 的边界内使用贴纸手势。

以下是我的代码:

func addStickers(image: UIImage) {

    gesture = "Stickers"

    imgSticker  = UIImageView(frame: CGRect.init(x: 0.0, y: 0.0, width: 80, height: 80))
    imgSticker.center = view.center
    imgSticker.image = image
    imgSticker.contentMode = UIViewContentMode.scaleAspectFill
    imgSticker.isUserInteractionEnabled = true

    self.view.addSubview(imgSticker)
    //imgImage.addSubview(imgSticker)

    panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(handlePanGesture(_:)))
    panGesture.delegate = self

    pinchGesture = UIPinchGestureRecognizer.init(target: self, action: #selector(handlePinchGesture(_:)))
    pinchGesture.delegate = self

    rotateGesture = UIRotationGestureRecognizer.init(target: self, action: #selector(handleRotateGesture(_:)))
    rotateGesture.delegate = self

    imgSticker.addGestureRecognizer(panGesture)
    imgSticker.addGestureRecognizer(pinchGesture)
    imgSticker.addGestureRecognizer(rotateGesture)
}

我调用这个函数和我的句柄方法如下:

                addStickers(image: #imageLiteral(resourceName: "Sticker1.png"))

func handlePanGesture(_ recognizer: UIPanGestureRecognizer) {

    if gesture == "Stickers" {
        let recognizerCenter = recognizer.location(in: self .view)
        imgSticker.center = recognizerCenter

    } else {
        let recognizerCenter = recognizer.location(in: self.view)
        txtLabel.center = recognizerCenter
    }

}

func handlePinchGesture(_ recognizer: UIPinchGestureRecognizer) {
    if gesture == "Stickers" {
         imgSticker.transform = imgSticker.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
         recognizer.scale = 1.0

    } else {
        txtLabel.transform = txtLabel.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
        recognizer.scale = 1.0
    }

}

func handleRotateGesture(_ recognizer: UIRotationGestureRecognizer) {

    if gesture == "Stickers" {
         imgSticker.transform = imgSticker.transform.rotated(by: recognizer.rotation)
         recognizer.rotation = 0.0

    } else {
        txtLabel.transform = txtLabel.transform.rotated(by: recognizer.rotation)
        recognizer.rotation = 0.0
    }

}

尝试将 self.view.addSubview(imgSticker) 中的 self.view 替换为正在编辑的图像的 ImageView,即您在其上粘贴贴纸的图像。希望能帮助到你。

所以,应该是这样的- imageView.addSubview(stickerOnImg)。我以前遇到过同样的问题,这对我有用。