欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【iOS】根据尺寸和比例缩放图片

程序员文章站 2022-04-09 09:21:42
...

根据尺寸

//根据指定尺寸缩放图片
-(UIImage *)imageCompressWithSize:(CGSize)size
{
**//    UIGraphicsBeginImageContext(size);   ///<用这个失真**
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);    ///<用这个不失真
    [self drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

之前用模拟器跑是没有问题,但是在真机运行时用这个方法缩小的图片过于模糊,最后发现使用UIGraphicsBeginImageContext(size);方法会造成失真,换成UIGraphicsBeginImageContextWithOptions(size, NO, 0.0); 就可以

根据比例缩放

//根据指定比例缩放图片
-(UIImage *)imageCompressWithScale:(CGFloat)scale
{
    
    CGSize size = self.size;
    CGFloat width = size.width;
    CGFloat height = size.height;
    CGFloat scaleWidth = width*scale;
    CGFloat scaleHeight = height*scale;
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(scaleWidth, scaleHeight), NO, 0.0);    ///<用这个不失真
    [self drawInRect:CGRectMake(0, 0, scaleWidth, scaleHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}