Cropping an UIImage

后端 未结 24 2111
轮回少年
轮回少年 2020-11-22 02:45

I\'ve got some code that resizes an image so I can get a scaled chunk of the center of the image - I use this to take a UIImage and return a small, square repre

24条回答
  •  余生分开走
    2020-11-22 03:45

    I wasn't satisfied with other solutions because they either draw several time (using more power than necessary) or have problems with orientation. Here is what I used for a scaled square croppedImage from a UIImage * image.

    CGFloat minimumSide = fminf(image.size.width, image.size.height);
    CGFloat finalSquareSize = 600.;
    
    //create new drawing context for right size
    CGRect rect = CGRectMake(0, 0, finalSquareSize, finalSquareSize);
    CGFloat scalingRatio = 640.0/minimumSide;
    UIGraphicsBeginImageContext(rect.size);
    
    //draw
    [image drawInRect:CGRectMake((minimumSide - photo.size.width)*scalingRatio/2., (minimumSide - photo.size.height)*scalingRatio/2., photo.size.width*scalingRatio, photo.size.height*scalingRatio)];
    
    UIImage *croppedImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    

提交回复
热议问题