论坛首页 移动开发技术论坛

UIImage等比缩放图像,按最大尺寸缩放

浏览 2383 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2012-08-01  
+ (UIImage*)scaleImage:(UIImage*)img toSize:(CGSize)size{
    int h = img.size.height;
    int w = img.size.width;
    
    if(h <= size.height && w <= size.width) {
        return img;
    } else {
        float destWith = 0.0f;
        float destHeight = 0.0f;
        
        float suoFang = (float)w/h;
        float suo = (float)h/w;
        if (w>h) {
            destWith = (float)size.width;
            destHeight = size.width * suo;
        }else {
            destHeight = (float)size.height;
            destWith = size.height * suoFang;
        }
        
        CGSize itemSize = CGSizeMake(destWith, destHeight);
        UIGraphicsBeginImageContext(itemSize);
        CGRect imageRect = CGRectMake(0, 0, destWith, destHeight);
        [img drawInRect:imageRect];
        UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return newImg;
    }
}
论坛首页 移动开发技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics