How to crop the UIImage?

后端 未结 7 1449
南笙
南笙 2020-11-30 01:50

I develop an application in which i process the image using its pixels but in that image processing it takes a lot of time. Therefore i want to crop UIImage (Only middle par

相关标签:
7条回答
  • 2020-11-30 02:33

    Using the function

    CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
    

    Here's an example code, used for a different purpose but clips ok.

    - (UIImage *)aspectFillToSize:(CGSize)size
    {
        CGFloat imgAspect = self.size.width / self.size.height;
        CGFloat sizeAspect = size.width/size.height;
    
        CGSize scaledSize;
    
            if (sizeAspect > imgAspect) { // increase width, crop height
                scaledSize = CGSizeMake(size.width, size.width / imgAspect);
            } else { // increase height, crop width
                scaledSize = CGSizeMake(size.height * imgAspect, size.height);
            }
        UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextClipToRect(context, CGRectMake(0, 0, size.width, size.height));
        [self drawInRect:CGRectMake(0.0f, 0.0f, scaledSize.width, scaledSize.height)];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    
    0 讨论(0)
提交回复
热议问题