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

时间:2017-09-11 06:58:54

标签: swift uiimageview gesture

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

enter image description here

以下是我的代码:

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
    }

}

1 个答案:

答案 0 :(得分:2)

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

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