UIImage: Resize, then Crop

后端 未结 16 2269
夕颜
夕颜 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:15

    I modified Brad Larson's Code. It will aspect fill the image in given rect.

    -(UIImage*) scaleAndCropToSize:(CGSize)newSize;
    {
        float ratio = self.size.width / self.size.height;
    
        UIGraphicsBeginImageContext(newSize);
    
        if (ratio > 1) {
            CGFloat newWidth = ratio * newSize.width;
            CGFloat newHeight = newSize.height;
            CGFloat leftMargin = (newWidth - newHeight) / 2;
            [self drawInRect:CGRectMake(-leftMargin, 0, newWidth, newHeight)];
        }
        else {
            CGFloat newWidth = newSize.width;
            CGFloat newHeight = newSize.height / ratio;
            CGFloat topMargin = (newHeight - newWidth) / 2;
            [self drawInRect:CGRectMake(0, -topMargin, newSize.width, newSize.height/ratio)];
        }
    
        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    

提交回复
热议问题