iOS 图片的缩放保真

2017-05-10  本文已影响0人  莫太极

需求背景

测试找到我说:“你这个图也太丑了,严重影响了整体的协调性,能不能改的小点” 我说:“这简单啊,小case”一分钟后,测试MM又来了:“图片怎么都失真了?” “我看看” 真的失真了,而且很明显的锯齿状...奇了个怪了
我是如是做的

- (UIImage *)imageScaled:(float)sizeScale
{
    CGSize size = CGSizeMake(self.size.width * sizeScale, self.size.height * sizeScale);

    UIGraphicsBeginImageContext(size);

    [self drawInRect:CGRectMake(0, 0, self.size.width * sizeScale, self.size.height * sizeScale)];
    
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}

想了想,点进UIGraphicsBeginImageContext里看了看

// UIImage context

// The following methods will only return a 8-bit per channel context in the DeviceRGB color space.
// Any new bitmap drawing code is encouraged to use UIGraphicsImageRenderer in leiu of this API.
UIKIT_EXTERN void     UIGraphicsBeginImageContext(CGSize size);
UIKIT_EXTERN void     UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) NS_AVAILABLE_IOS(4_0);
UIKIT_EXTERN UIImage* __nullable UIGraphicsGetImageFromCurrentImageContext(void);
UIKIT_EXTERN void     UIGraphicsEndImageContext(void); 

目光聚焦在了UIKIT_EXTERN void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) NS_AVAILABLE_IOS(4_0); 这个方法上

试了一会,最后成型

#pragma mark - 缩放图片不失真
- (UIImage *)imageScaled:(float)sizeScale
{
    CGSize size = CGSizeMake(self.size.width * sizeScale, self.size.height * sizeScale);
    
    if([[UIScreen mainScreen] scale] == 3.0){
        UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
    }else  if([[UIScreen mainScreen] scale] == 2.0){
        UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }else{
        UIGraphicsBeginImageContext(size);
    }
    [self drawInRect:CGRectMake(0, 0, self.size.width * sizeScale, self.size.height * sizeScale)];
    
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}

Prefect 测试mm也很满足(😌)

再回看这个方法 UIKIT_EXTERN void UIGraphicsBeginImageContextWithOptions(CGSize size, BOOL opaque, CGFloat scale) NS_AVAILABLE_IOS(4_0);

最后插句嘴 ,我这个方法是写在分类里的

如果你想直接来,可以这样

- (UIImage *)scaleImage:(UIImage *)orginImage withScale:(float)sizeScale
{
    CGSize size = CGSizeMake(orginImage.size.width * sizeScale, orginImage.size.height * sizeScale);
    
    if([[UIScreen mainScreen] scale] == 3.0){ 
               UIGraphicsBeginImageContextWithOptions(size, NO, 3.0);
    }else if([[UIScreen mainScreen] scale] == 2.0){  
              UIGraphicsBeginImageContextWithOptions(size, NO, 2.0);
    }else{
        UIGraphicsBeginImageContext(size);
    }
    [orginImage drawInRect:CGRectMake(0, 0, orginImage.size.width * sizeScale, orginImage.size.height * sizeScale)];
    
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage;
    
}
上一篇下一篇

猜你喜欢

热点阅读