图像以矩形形状裁剪并且移动

时间:2014-07-30 11:35:12

标签: ios image imageview crop

我想裁剪一个矩形大小的UIImageView它应该是可调整大小的,请任何人帮助我,我正在努力。

1 个答案:

答案 0 :(得分:0)

您可以使用以下代码添加平移手势,您可以从中移动图像视图和捏合手势,通过该手势可以调整图像大小

-(void)addGesture {
    UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(move:)];
    [panRecognizer setMinimumNumberOfTouches:1];
    [panRecognizer setMaximumNumberOfTouches:1];
    [imgView addGestureRecognizer:panRecognizer];

     UIPinchGestureRecognizer *pinchRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(resize:)];
        [imgView addGestureRecognizer:pinchRecognizer];

}

-(void)move:(id)sender {
    [self.view bringSubviewToFront:[(UIPanGestureRecognizer*)sender view]];
    CGPoint translatedPoint = [(UIPanGestureRecognizer*)sender translationInView:self.view];

    if ([(UIPanGestureRecognizer*)sender state] == UIGestureRecognizerStateBegan) {
        firstX = [[sender view] center].x;
        firstY = [[sender view] center].y;
    }

    translatedPoint = CGPointMake(firstX+translatedPoint.x, firstY);

    [[sender view] setCenter:translatedPoint];
}

- (void)resize:(UIPinchGestureRecognizer *)recognizer
{

    if([recognizer state] == UIGestureRecognizerStateBegan) {
        _lastScale = 1.0;
        if ([recognizer numberOfTouches] >= 2) { //should always be true when using a PinchGR
            CGPoint touch1 = [recognizer locationOfTouch:0 inView:self.imageForEditing];
            CGPoint touch2 = [recognizer locationOfTouch:1 inView:self.imageForEditing];
            CGPoint mid;
            mid.x = ((touch2.x - touch1.x) / 2) + touch1.x;
            mid.y = ((touch2.y - touch1.y) / 2) + touch1.y;
            CGSize imageViewSize = self.imageForEditing.frame.size;
            CGPoint anchor;
            anchor.x = mid.x / imageViewSize.width;
            anchor.y = mid.y / imageViewSize.height;
            self.imageForEditing.layer.anchorPoint = anchor;
        }
    }

    CGFloat scale = 1.0 - (_lastScale - [recognizer scale]);

    CGAffineTransform currentTransform = self.imageForEditing.transform;
    CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);

    [self.imageForEditing setTransform:newTransform];

    _lastScale = [recognizer scale];


}