How to crop a UIImageView to a new UIImage in 'aspect fit' mode?

后端 未结 4 1128
一生所求
一生所求 2020-12-28 10:51

\"enter

I would like to create a new UIImage by cropping the image inside a UIImageVie

4条回答
  •  心在旅途
    2020-12-28 10:54

    I know the answer has been but I had some problems getting above right so, I wont to post my solution too.

    The problem is the image is scaled with a aspect fit, but we know the scale factor for both the width and the height. Then we can calculate the right cropping rectangle pretty easy:

    -(UIImage*)crop:(CGRect)frame
    {
        // Find the scalefactors  UIImageView's widht and height / UIImage width and height
        CGFloat widthScale = self.bounds.size.width / self.image.size.width;
        CGFloat heightScale = self.bounds.size.height / self.image.size.height;
    
        // Calculate the right crop rectangle 
        frame.origin.x = frame.origin.x * (1 / widthScale);
        frame.origin.y = frame.origin.y * (1 / heightScale);
        frame.size.width = frame.size.width * (1 / widthScale);
        frame.size.height = frame.size.height * (1 / heightScale);
    
        // Create a new UIImage
        CGImageRef imageRef = CGImageCreateWithImageInRect(self.image.CGImage, frame);
        UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
        CGImageRelease(imageRef);
    
        return croppedImage;
    }
    

提交回复
热议问题