iPhone - How do you make a resizable rectangle for cropping images?

陌路散爱 提交于 2019-11-28 07:51:59
wkw

bookmark my question which is exactly the same.

I got as far as moving around my cropping view and having it show the portion of the image correctly, but dealing with the scrollview zooming is a work in progress. presently I have an imageview and plain UIView layered in the UIScrollview, then outside of the scrollview and at a higher level is my custom cropping UIView. I implement the touches methods to deal with dragging it around, and also drawRect:

- (void)drawRect:(CGRect)rect {
    // Drawing code
    if( self.image == nil )
        return;

    CGPoint offset = scrollView.contentOffset;
    clipRect = CGRectOffset(self.frame, offset.x, offset.y);

    UIImage *croppedImage = [image croppedImage:clipRect];
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [croppedImage drawAtPoint:CGPointMake(0, 0)];
}

Note: my cropping view is NOT a descendant of UIImageView, it's just UIView with a reference to the underlying image from the other view.

"croppedImage" is a category on UIImage and pretty simple:

@implementation UIImage (Resize)
- (UIImage *)croppedImage:(CGRect)bounds {
    CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], bounds);
    UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
    CGImageRelease(imageRef);
    return croppedImage;
}
...
@end

I've implemented a few of the UIScrollViewDelegate methods and pass through scrolling activity so I can keep my cropping view in sync. Zooming is passed along too, but as mentioned, not working as desired yet.

Another Note: I don't think it's necessary to waste the time generating a new UIImage with the cropped area every time as the same should be possible with

CGImageRef imageRef = CGImageCreateWithImageInRect([yourImage CGImage], bounds);
and 
CGContextDrawImage(ctx, clipRect, imageRef);

Quartz is the 'marketing term' for Core Graphics, and that's where you should start. You'll want to use a UIView (full custom drawing in -drawRect:), trap and track its touches, and then draw the result. You can get the current Graphics Context using UIGraphicsGetCurrentContext(). That should be enough to get you started!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!