美文网首页
IOS平台生成图片缩略图的两种方案

IOS平台生成图片缩略图的两种方案

作者: 傲骨天成科技 | 来源:发表于2016-05-12 22:24 被阅读2046次

    只写出关键部分,其它部分自己添加既可

    1.自动缩放到指定大小

    • (UIImage *)thumbnailWithImage:(UIImage *)image size:(CGSize)asize

    {

    UIImage *newimage;

    if (nil == image) {

    newimage = nil;

    }

    else{

    UIGraphicsBeginImageContext(asize);

    [image drawInRect:CGRectMake(0, 0, asize.width, asize.height)];

    newimage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    }

    return newimage;

    }

    2.保持原来的长宽比,生成一个缩略图

    • (UIImage *)thumbnailWithImageWithoutScale:(UIImage *)image size:(CGSize)asize

    {

    UIImage *newimage;

    if (nil == image) {

    newimage = nil;

    }

    else{

    CGSize oldsize = image.size;

    CGRect rect;

    if (asize.width/asize.height > oldsize.width/oldsize.height) {

    rect.size.width = asize.height*oldsize.width/oldsize.height;

    rect.size.height = asize.height;

    rect.origin.x = (asize.width - rect.size.width)/2;

    rect.origin.y = 0;

    }

    else{

    rect.size.width = asize.width;

    rect.size.height = asize.width*oldsize.height/oldsize.width;

    rect.origin.x = 0;

    rect.origin.y = (asize.height - rect.size.height)/2;

    }

    UIGraphicsBeginImageContext(asize);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);

    UIRectFill(CGRectMake(0, 0, asize.width, asize.height));//clear background

    [image drawInRect:rect];

    newimage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    }

    return newimage;

    }

    相关文章

      网友评论

          本文标题: IOS平台生成图片缩略图的两种方案

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