通过手势识别器操作后裁剪UIImageView

时间:2016-01-12 02:46:54

标签: ios objective-c uiimageview uigesturerecognizer

我有问题解决这个问题!我看到的所有示例都与scrollView有关,我没有使用它。在通过捏合,平移和旋转操作图像后,我需要在预定的CGRect区域内裁剪图像。我在下面的代码在左上角裁剪未操作的图像。

澄清pendantCanvasView是视图(容器),pendantImageView是pendantCanvasView的子类。 PendantFrame只是一个CGRect,它在我要裁剪的pendantImageView中有rect的坐标。

有人可以帮助我吗?

这是我到目前为止的代码:

- (void)addMoveImageToolbox {

   UIPinchGestureRecognizer *pinchRec = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(handlePinch:)];
   [self.pendantCanvasView addGestureRecognizer:pinchRec];

   UIRotationGestureRecognizer *rotateRec = [[UIRotationGestureRecognizer alloc]initWithTarget:self action:@selector(handleRotate:)];
   [self.pendantCanvasView addGestureRecognizer:rotateRec];

   UIPanGestureRecognizer *panRec = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
   [self.pendantCanvasView addGestureRecognizer:panRec];
}

- (void)handlePinch:(UIPinchGestureRecognizer*)pinch {
   self.pendantImageView.transform = CGAffineTransformScale(self.pendantImageView.transform, pinch.scale, pinch.scale);
   self.zoomScale = pinch.scale;
   pinch.scale = 1;
}

- (void)handleRotate:(UIRotationGestureRecognizer*)rotate {
   self.pendantImageView.transform =   CGAffineTransformRotate(self.pendantImageView.transform, rotate.rotation);
   rotate.rotation = 0;
}

- (void)handlePan:(UIPanGestureRecognizer *)pan {

   CGPoint translation = [pan translationInView:self.pendantCanvasView];
   self.pendantImageView.center = CGPointMake(self.pendantImageView.center.x + translation.x,
                                     self.pendantImageView.center.y + translation.y);
   [pan setTranslation:CGPointMake(0, 0) inView:self.pendantImageView];
}

裁剪方法:

- (UIImage *)captureScreenInRect {

   UIGraphicsBeginImageContextWithOptions(pendantFrame.size, NO, [UIScreen mainScreen].scale);
   [self.pendantCanvasView drawViewHierarchyInRect:pendantFrame afterScreenUpdates:YES];
   UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();self.pendantImageView.constraints

   return image;
}

1 个答案:

答案 0 :(得分:0)

我相信drawViewHierarchyInRect会重新渲染视图层次结构,因此可能会丢失对imageView的更改。

您可以尝试使用snapshotViewAfterScreenUpdates。

我不确定pendantCanvasView,pendantImageView和pendantFrame之间的关系是什么,但是可以使用一个或另一个的layer属性的renderInContext方法来获取裁剪的图像。