UIImage: Resize, then Crop

后端 未结 16 2273
夕颜
夕颜 2020-11-22 11:51

I\'ve been bashing my face into this one for literally days now and even though I feel constantly that I am right on the edge of revelation, I simply cannot achieve my goal.

16条回答
  •  渐次进展
    2020-11-22 12:09

    - (UIImage*)imageScale:(CGFloat)scaleFactor cropForSize:(CGSize)targetSize
    {
        targetSize = !targetSize.width?self.size:targetSize;
        UIGraphicsBeginImageContext(targetSize); // this will crop
    
        CGRect thumbnailRect = CGRectZero;
    
        thumbnailRect.size.width  = targetSize.width*scaleFactor;
        thumbnailRect.size.height = targetSize.height*scaleFactor;
        CGFloat xOffset = (targetSize.width- thumbnailRect.size.width)/2;
        CGFloat yOffset = (targetSize.height- thumbnailRect.size.height)/2;
        thumbnailRect.origin = CGPointMake(xOffset,yOffset);
    
        [self drawInRect:thumbnailRect];
    
        UIImage *newImage  = UIGraphicsGetImageFromCurrentImageContext();
    
        if(newImage == nil)
        {
            NSLog(@"could not scale image");
        }
    
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    

    Below the example of work: Left image - (origin image) ; Right image with scale x2

    enter image description here

    If you want to scale image but retain its frame(proportions), call method this way:

    [yourImage imageScale:2.0f cropForSize:CGSizeZero];
    

提交回复
热议问题