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

后端 未结 4 1131
一生所求
一生所求 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 11:02

    Based on my other answer to a similar question I have written this method for a UIImageView category:

    -(CGRect) cropRectForFrame:(CGRect)frame
    {
        NSAssert(self.contentMode == UIViewContentModeScaleAspectFit, @"content mode must be aspect fit");
    
        CGFloat widthScale = self.bounds.size.width / self.image.size.width;
        CGFloat heightScale = self.bounds.size.height / self.image.size.height;
    
        float x, y, w, h, offset;
        if (widthScale

    You can pass in the frame of your green rect (assuming it is a subview of the image view) and get the crop rect back for cropping the UIImage. Note that it only works for 'aspect fit' mode! I haven't tested it though. So, tell me if it works!

提交回复
热议问题