开发者

Get zoomed image from UIImageView

I am using a UIImageview inside a UIScrollView to let users pinch and zoom the image. I now want to get the image which the user has modified (small or zoomed in). How can I do this?

Thanks.

OK, am trying something new now. Can I get a thumbnail from an image from somewhere in between? I can get the thumbn开发者_C百科ail from (0,0) for a fixed size. Can I get it from say (10, 20) or (30, 30)? Thanks again. I tried using CGImageCreateWithImageInRect with a rect having these values for x and y. But it gives me an image from point 0,0


When you zoom UIImageView object inside UIScrollView, you change only UIImageView frame, but UIImage in image property remains unchanged.

if you only want to show this image scaled in some other UIImageView, you should not change UIImage size, just set your new UIImageView frame same as frame of zoomed UIImageView from UIScrollView and use same image:

UIImageView * ImageViewOnScroll;
//set image and zoom it
... 
UIImageView * newImageView = [[UIImageView alloc] initWithImage:ImageViewOnScroll.image];
newImageView.frame = ImageViewOnScroll.frame;

if for some reason you want to create new UIImage with changed size you can do it for example with following simple method:

UIImage * resizeImage(UIImage * img, CGSize newSize){
    UIGraphicsBeginImageContext(newSize);

    //or other CGInterpolationQuality value
    CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationDefault);

    [img drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


I solved it by creating a tiny UIImage extension (Swift 5.2 compatible) that works perfectly when you have UIImageView embedded in UIScrollView:

extension UIImage {

    func crop(from scrollView: UIScrollView) -> UIImage? {
            let zoom: CGFloat = 1.0 / scrollView.zoomScale
            let xOffset: CGFloat = (size.width / scrollView.contentSize.width) * scrollView.contentOffset.x
            let yOffset: CGFloat = (size.height / scrollView.contentSize.height) * scrollView.contentOffset.y

            let cropRect = CGRect(xOffset * scale, yOffset * scale, size.width * zoom * scale, size.height * zoom * scale)

            guard let croppedImageRef = cgImage?.cropping(to: cropRect) else { return nil }
            let croppedImage = UIImage(cgImage: croppedImageRef, scale: scale, orientation: imageOrientation)

            return croppedImage
    }

}

Use it to get zoomed part of the image:

let croppedImage = sourceImage.crop(from: scrollView)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜