iOS : Save image with custom resolution

前端 未结 9 2026
长发绾君心
长发绾君心 2020-12-08 03:42

Hi I am try to capture a view then save as an image into Photo Library , but I need create a custom resolution for captured image , here is my code but when app saves the im

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 03:58

    You can use that :

    UIImageExtras.h

    @interface UIImage (Extras)
    -(UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize;
    @end
    

    UIImageExtras.m

    #import "UIImageExtras.h"
    
    @implementation UIImage (Extras)
    
    - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
    {
    //Image de base
    UIImage *sourceImage = self;
    //Image redimenssionnée
    UIImage *newImage = nil; 
    
    //Taille de l'image de base
    CGSize imageSize = sourceImage.size;
    //Longueur et largeur 
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    //Dimension désirée
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    
    //Echelle...
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    //Si taille des image est différentes on redimensionne de facon proportionnelle
    if (CGSizeEqualToSize(imageSize, targetSize) == NO) 
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
    
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
    
        //Centre l'image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; 
        }
        else if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
        }       
    
        UIGraphicsBeginImageContext(targetSize);
    
        CGRect thumbnailRect = CGRectZero;
        thumbnailRect.origin = thumbnailPoint;
        thumbnailRect.size.width  = scaledWidth;
        thumbnailRect.size.height = scaledHeight;
    
        [sourceImage drawInRect:thumbnailRect];
    
        newImage = UIGraphicsGetImageFromCurrentImageContext();
        if(newImage == nil) 
            NSLog(@"could not scale image");
    
        UIGraphicsEndImageContext();
    
        return newImage;
    }
    @end
    

提交回复
热议问题