美文网首页iOS
按比例缩放,size 是你要把图显示到多大区域

按比例缩放,size 是你要把图显示到多大区域

作者: 三浦蒼介 | 来源:发表于2018-10-30 11:18 被阅读0次

    +(UIImage*)imageCompressFitSizeScale:(UIImage*)sourceImage targetSize:(CGSize)size

    {

        UIImage*newImage =nil;

        CGSizeimageSize = sourceImage.size;

        CGFloatwidth = imageSize.width;

        CGFloatheight = imageSize.height;

        CGFloattargetWidth = size.width;

        CGFloattargetHeight = size.height;

        CGFloatscaleFactor =0.0;

        CGFloatscaledWidth = targetWidth;

        CGFloatscaledHeight = targetHeight;

        CGPointthumbnailPoint =CGPointMake(0.0,0.0);

        if(CGSizeEqualToSize(imageSize,size)==NO){

            CGFloatwidthFactor = targetWidth / width;

            CGFloatheightFactor = targetHeight / height;

            if(widthFactor > heightFactor){

                scaleFactor = widthFactor;

            }

            else{

                scaleFactor = heightFactor;

            }

            scaledWidth = width * scaleFactor;

            scaledHeight = height * scaleFactor;

            if(widthFactor > heightFactor){

                thumbnailPoint.y=(targetHeight - scaledHeight)*0.5;

            }elseif(widthFactor < heightFactor){

                thumbnailPoint.x=(targetWidth - scaledWidth)*0.5;

            }

        }

        UIGraphicsBeginImageContext(size);

        CGRectthumbnailRect =CGRectZero;

        thumbnailRect.origin= thumbnailPoint;

        thumbnailRect.size.width= scaledWidth;

        thumbnailRect.size.height= scaledHeight;

        [sourceImagedrawInRect:thumbnailRect];

        newImage =UIGraphicsGetImageFromCurrentImageContext();

        if(newImage ==nil){

            NSLog(@"scale image fail");

        }

        UIGraphicsEndImageContext();

        returnnewImage;

    }

    -(UIImage*)scaleToSize:(CGSize)size

    {

    //创建一个bitmap的context

    // 并把它设置成为当前正在使用的context

    //Determine whether the screen is retina

    if([[UIScreen mainScreen]scale]== 2.0){

    UIGraphicsBeginImageContextWithOptions(size,NO,2.0);

    }else{

    UIGraphicsBeginImageContext(size);

    }

    // 绘制改变大小的图片

    [self drawInRect:CGRectMake(0,0,size.width,size.height)];

    // 从当前context中创建一个改变大小后的图片

    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    //使当前的context出堆栈

    UIGraphicsEndImageContext();

    // 返回新的改变大小后的图片

    return scaledImage;

    }

    相关文章

      网友评论

        本文标题:按比例缩放,size 是你要把图显示到多大区域

        本文链接:https://www.haomeiwen.com/subject/eyzwtqtx.html