神刀安全网

UIImage 分类大集合

UIImage 分类大集合

@(iOS)[UIImage]

[TOC]

修正图片方向

  • 这个使用很常见,特别是在上传图片时,一定要记得修正方向,不然安卓或者服务端下载下来方向就不对了。
  • 当然这个分类方法是已经有大神写出来了。
  • image = [image fixOrientation];
/**  *  修正图片方向  *  *  @return 修改后的图片  */ - (UIImage *)fixOrientation {      // No-op if the orientation is already correct     if (self.imageOrientation == UIImageOrientationUp) return self;      // We need to calculate the proper transformation to make the image upright.     // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.     CGAffineTransform transform = CGAffineTransformIdentity;      switch (self.imageOrientation) {         case UIImageOrientationDown:         case UIImageOrientationDownMirrored:             transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);             transform = CGAffineTransformRotate(transform, M_PI);             break;          case UIImageOrientationLeft:         case UIImageOrientationLeftMirrored:             transform = CGAffineTransformTranslate(transform, self.size.width, 0);             transform = CGAffineTransformRotate(transform, M_PI_2);             break;          case UIImageOrientationRight:         case UIImageOrientationRightMirrored:             transform = CGAffineTransformTranslate(transform, 0, self.size.height);             transform = CGAffineTransformRotate(transform, -M_PI_2);             break;         case UIImageOrientationUp:         case UIImageOrientationUpMirrored:             break;     }      switch (self.imageOrientation) {         case UIImageOrientationUpMirrored:         case UIImageOrientationDownMirrored:             transform = CGAffineTransformTranslate(transform, self.size.width, 0);             transform = CGAffineTransformScale(transform, -1, 1);             break;          case UIImageOrientationLeftMirrored:         case UIImageOrientationRightMirrored:             transform = CGAffineTransformTranslate(transform, self.size.height, 0);             transform = CGAffineTransformScale(transform, -1, 1);             break;         case UIImageOrientationUp:         case UIImageOrientationDown:         case UIImageOrientationLeft:         case UIImageOrientationRight:             break;     }      // Now we draw the underlying CGImage into a new context, applying the transform     // calculated above.     CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,                                              CGImageGetBitsPerComponent(self.CGImage), 0,                                              CGImageGetColorSpace(self.CGImage),                                              CGImageGetBitmapInfo(self.CGImage));     CGContextConcatCTM(ctx, transform);     switch (self.imageOrientation) {         case UIImageOrientationLeft:         case UIImageOrientationLeftMirrored:         case UIImageOrientationRight:         case UIImageOrientationRightMirrored:             // Grr...             CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);             break;          default:             CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);             break;     }      // And now we just create a new UIImage from the drawing context     CGImageRef cgimg = CGBitmapContextCreateImage(ctx);     UIImage *img = [UIImage imageWithCGImage:cgimg];     CGContextRelease(ctx);     CGImageRelease(cgimg);     return img; }

具体解析,参考这篇文字

指定颜色生成图片

  • 由颜色UIColor直接生成对应的图片,当然要指定尺寸。
  • image = [UIImage imageWithColor:[UIColor colorWithRed:30 green:190 blue:100 alpha:0.1] andSize:CGSizeMake(100, 100)];
/**  *  返回指定颜色生成的图片  *  *  @param color 颜色  *  @param size  尺寸  *  *  @return  */ + (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size {     CGRect rect = CGRectMake(0, 0, size.width, size.height);     UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);     CGContextRef context = UIGraphicsGetCurrentContext();     CGContextSetFillColorWithColor(context, color.CGColor);     CGContextFillRect(context, rect);      UIImage *img = UIGraphicsGetImageFromCurrentImageContext();      UIGraphicsEndImageContext();      return img; }  /**  *  获取指定尺寸(50*50)的图片  *  *  @param color 图片颜色  *  @param name  文本,居中显示  *  *  @return  */ + (UIImage *)imageWithColor:(UIColor *)color text:(NSString *)name {     CGRect rect = CGRectMake(0, 0, 50, 50);     UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0);     CGContextRef context = UIGraphicsGetCurrentContext();     CGContextSetFillColorWithColor(context, color.CGColor);     CGContextFillRect(context, rect);     [name drawAtPoint:CGPointMake(10, 15) withAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]}];     UIImage *img = UIGraphicsGetImageFromCurrentImageContext();      UIGraphicsEndImageContext();      return img; }

图片模糊

  • 生成带有模糊效果的图片,可以直接又UIImage生成,或者直接生成纯色的模糊图片。还有边框
  • 图片模糊
UIImage 分类大集合
Snip20160905_1.png

UIImage 分类大集合
Snip20160905_2.png

  • 纯色图片模糊
    UIImage 分类大集合
    Snip20160905_4.png

    UIImage 分类大集合
    Snip20160905_5.png

/// 对图片进行模糊处理 + (UIImage *)gaussianBlurImage:(UIImage *)image andInputRadius:(CGFloat)radius {     if (!image) {         return nil;     }      CIContext *context = [CIContext contextWithOptions:nil];     CIImage *inputImage = [CIImage imageWithCGImage:image.CGImage];      CIFilter *filter = [CIFilter filterWithName:@"CIGaussianBlur"];     [filter setValue:inputImage forKey:kCIInputImageKey];     [filter setValue:[NSNumber numberWithFloat:radius] forKey:@"inputRadius"];     CIImage *result = [filter valueForKey:kCIOutputImageKey];     CGImageRef cgImage = [context createCGImage:result fromRect:[inputImage extent]];     UIImage *resultImage = [UIImage imageWithCGImage:cgImage];     CGImageRelease(cgImage);      return resultImage; }  /// 由颜色生成模糊图片 + (UIImage *)gaussianBlurImageWithColor:(UIColor *)color andSize:(CGSize)size andInputRadius:(CGFloat)radius {     UIImage *image = [UIImage imageWithColor:color andSize:size];     if (image) {         return [UIImage gaussianBlurImage:image andInputRadius:radius];     }     else {         return nil;     } }

转换#FFFFFF格式颜色

  • 直接生成UIColor类型的颜色,可以指定透明通道
/**  *  转换#FFFFFF格式颜色  *  *  @param string 颜色字符串  *  *  @return  */ + (UIColor *)RGBColor:(NSString *)string {     if ([string rangeOfString:@"#"].location != NSNotFound) {         string = [string stringByReplacingOccurrencesOfString:@"#" withString:@""];     }      // 十六进制字符串转成整形。     long colorLong = strtoul([string cStringUsingEncoding:NSUTF8StringEncoding], 0, 16);     // 通过位与方法获取三色值     int R = (colorLong & 0xFF0000 )>>16;     int G = (colorLong & 0x00FF00 )>>8;     int B = colorLong & 0x0000FF;      //string转color     UIColor *wordColor = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:1.0];     return wordColor; }   /**  *  转换#FFFFFF格式颜色  *  *  @param string 颜色只付出  *  @param alpha  指定透明  *  *  @return 颜色  */ + (UIColor *)RGBColor:(NSString *)string alpha:(CGFloat )alpha{     if ([string rangeOfString:@"#"].location != NSNotFound) {         string = [string stringByReplacingOccurrencesOfString:@"#" withString:@""];     }      // 十六进制字符串转成整形。     long colorLong = strtoul([string cStringUsingEncoding:NSUTF8StringEncoding], 0, 16);     // 通过位与方法获取三色值     int R = (colorLong & 0xFF0000 )>>16;     int G = (colorLong & 0x00FF00 )>>8;     int B = colorLong & 0x0000FF;      //string转color     UIColor *wordColor = [UIColor colorWithRed:R/255.0 green:G/255.0 blue:B/255.0 alpha:alpha];     return wordColor; }

透明边框效果图片

  • 给图片添加透明通道,实现透明边框效果
    UIImage 分类大集合
    Snip20160905_6.png

    UIImage 分类大集合
    Snip20160905_7.png

#pragma mark - 透明效果图片 /// 如果含有透明通道就返回TRUE - (BOOL)hasAlpha {     // 获取图片的Alpha信息     CGImageAlphaInfo alpha = CGImageGetAlphaInfo(self.CGImage);     // 只要满足一下一种就含有透明通道     return (alpha == kCGImageAlphaFirst ||             alpha == kCGImageAlphaLast ||             alpha == kCGImageAlphaPremultipliedFirst ||             alpha == kCGImageAlphaPremultipliedLast); }  /// 如果不存在透明通道就添加透明通道并返回结果 - (UIImage *)imageWithAlpha {     if ([self hasAlpha]) {         return self; // 已有,直接返回     }      CGFloat scale = MAX(self.scale, 1.0f);     CGImageRef imageRef = self.CGImage;     size_t width = CGImageGetWidth(imageRef)*scale;     size_t height = CGImageGetHeight(imageRef)*scale;      // 创建位图上下文     CGContextRef offscreenContext =     CGBitmapContextCreate(NULL, // 渲染内存,为NULL表示由Quartz自动分配                           width,//                           height,                           8,// bitsPerComponent 每个像素组件的位数                           0,// 位图每行的字节数,0表示自动                           CGImageGetColorSpace(imageRef),// 颜色空间                           kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);// 位图信息,这里添加透明通道       // 绘制图片     CGContextDrawImage(offscreenContext, CGRectMake(0, 0, width, height), imageRef);     CGImageRef imageRefWithAlpha = CGBitmapContextCreateImage(offscreenContext);     UIImage *imageWithAlpha = [UIImage imageWithCGImage:imageRefWithAlpha scale:self.scale orientation:UIImageOrientationUp];      // 清理内存     CGContextRelease(offscreenContext);     CGImageRelease(imageRefWithAlpha);      return imageWithAlpha; }  /// 给图片增加透明边框,将图片进行缩放 - (UIImage *)transparentBorderImage:(NSUInteger)borderSize {     // 如果没有透明通道,那就增加一个     UIImage *image = [self imageWithAlpha];     CGFloat scale = MAX(self.scale, 1.0f);     NSUInteger scaledBorderSize = borderSize * scale;     // 新图片大小     CGRect newRect = CGRectMake(0, 0, image.size.width * scale + scaledBorderSize * 2, image.size.height * scale + scaledBorderSize * 2);      // 创建位图     CGContextRef bitmap = CGBitmapContextCreate(NULL,                                                 newRect.size.width,                                                 newRect.size.height,                                                 CGImageGetBitsPerComponent(self.CGImage),                                                 0,                                                 CGImageGetColorSpace(self.CGImage),                                                 CGImageGetBitmapInfo(self.CGImage));      // 绘制位图,预留一个空白的外边框     CGRect imageLocation = CGRectMake(scaledBorderSize, scaledBorderSize, image.size.width*scale, image.size.height*scale);     CGContextDrawImage(bitmap, imageLocation, self.CGImage);     CGImageRef borderImageRef = CGBitmapContextCreateImage(bitmap);      // 创建图片掩码,边框透明,然后和原图合并     CGImageRef maskImageRef = [self newBorderMask:scaledBorderSize size:newRect.size];     CGImageRef transparentBorderImageRef = CGImageCreateWithMask(borderImageRef, maskImageRef);     UIImage *transparentBorderImage = [UIImage imageWithCGImage:transparentBorderImageRef scale:self.scale orientation:UIImageOrientationUp];      // Clean up     CGContextRelease(bitmap);     CGImageRelease(borderImageRef);     CGImageRelease(maskImageRef);     CGImageRelease(transparentBorderImageRef);      return transparentBorderImage; }   *  创建透明边框  *  *  @param borderSize 边框宽度  *  @param size       尺寸  *  *  @return  */ - (CGImageRef)newBorderMask:(NSUInteger)borderSize size:(CGSize)size {     // 颜色空间-灰度     CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();      // 图像上下文     CGContextRef maskContext = CGBitmapContextCreate(NULL,                                                      size.width,                                                      size.height,                                                      8, // 8-bit grayscale                                                      0,                                                      colorSpace,                                                      kCGBitmapByteOrderDefault | kCGImageAlphaNone);      // 透明     CGContextSetFillColorWithColor(maskContext, [UIColor blackColor].CGColor);     CGContextFillRect(maskContext, CGRectMake(0, 0, size.width, size.height));      // 中心不透明     CGContextSetFillColorWithColor(maskContext, [UIColor whiteColor].CGColor);     CGContextFillRect(maskContext, CGRectMake(borderSize, borderSize, size.width - borderSize * 2, size.height - borderSize * 2));      // 获取图片掩码     CGImageRef maskImageRef = CGBitmapContextCreateImage(maskContext);      // 清理     CGContextRelease(maskContext);     CGColorSpaceRelease(colorSpace);      return maskImageRef; }

UIImage缩放

  • UIImage等比例缩放、UIImage自定长宽缩放
    UIImage *image = [UIImage imageNamed:@"1"];     NSLog(@"%@",NSStringFromCGSize(image.size));// {1920, 1080}     image = [UIImage reSizeImage:image toSize:CGSizeMake(100, 100)];     // image = [UIImage scaleImage:image toScale:0.5];//{960, 540}     NSLog(@"%@",NSStringFromCGSize(image.size));//{100, 100}
//UIImage等比例缩放 +(UIImage *)scaleImage:(UIImage *)image toScale:(CGFloat)scaleSize  {      UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));     [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];     UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();     UIGraphicsEndImageContext();      return scaledImage;  }  //UIImage自定长宽缩放 +(UIImage *)reSizeImage:(UIImage *)image toSize:(CGSize)reSize  {     UIGraphicsBeginImageContext(CGSizeMake(reSize.width, reSize.height));     [image drawInRect:CGRectMake(0, 0, reSize.width, reSize.height)];     UIImage *reSizeImage = UIGraphicsGetImageFromCurrentImageContext();     UIGraphicsEndImageContext();      return reSizeImage;  }

圆形图片

  • 圆形图片经常用的,直接写一个分类,方便
#pragma mark - Cut /**  *  图片剪切为圆形  *  *  @param originalImage 原始图片  *  *  @return 剪切后的圆形图片  */ - (UIImage *)roundImage{      //获取size     CGSize size = [self sizeFromImage:self];      CGRect rect = (CGRect){CGPointZero,size};      //新建一个图片图形上下文     UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);      //获取上下文     CGContextRef ctx = UIGraphicsGetCurrentContext();      //绘制圆形路径     CGContextAddEllipseInRect(ctx, rect);      //剪裁上下文     CGContextClip(ctx);      //绘制图片     [self drawInRect:rect];      //取出图片     UIImage *roundImage = UIGraphicsGetImageFromCurrentImageContext();      //结束上下文     UIGraphicsEndImageContext();      return roundImage; }   - (CGSize)sizeFromImage:(UIImage *)image{      CGSize size = image.size;      CGFloat wh =MIN(size.width, size.height);      return CGSizeMake(wh, wh); }

截屏/截图

  • 屏幕截图
  • 从指定的view截图
/*  *  直接截屏  */ + (UIImage *)cutScreen{     return [self cutFromView:[UIApplication sharedApplication].keyWindow]; }  /**  *  从给定UIView中截图:UIView转UIImage  */ + (UIImage *)cutFromView:(UIView *)view{      //开启图形上下文     UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0f);      //获取上下文     CGContextRef context = UIGraphicsGetCurrentContext();      //在新建的图形上下文中渲染view的layer     [view.layer renderInContext:context];      [[UIColor clearColor] setFill];      //获取图片     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();      //关闭图形上下文     UIGraphicsEndImageContext();      return image;  }  /**  *  从给定UIImage和指定Frame截图:  */ - (UIImage *)cutWithFrame:(CGRect)frame{      //创建CGImage     CGImageRef cgimage = CGImageCreateWithImageInRect(self.CGImage, frame);      //创建image     UIImage *newImage=[UIImage imageWithCGImage:cgimage];      //释放CGImage     CGImageRelease(cgimage);      return newImage; }

水印

  • 图片水印,将图片绘制到一张图片任意位置
  • 文字水印,将文字绘制到一张图片任意位置
UIImage 分类大集合
Snip20160907_10.png

UIImage 分类大集合
Snip20160907_11.png

//  图片水印 image = [image waterWithWaterImage:[UIImage imageNamed:@"2"] direction:ImageWaterDirectCenter waterSize:CGSizeMake(100, 100) marginXY:CGPointMake(0, 0)]; // 文字水印 image =  [image waterWithText:@"哈哈哈" direction:ImageWaterDirectCenter fontColor:[UIColor blackColor] fontPoint:60 marginXY:CGPointMake(0, 0)];
/*  *  水印方向  */ typedef enum {      //左上     ImageWaterDirectTopLeft=0,      //右上     ImageWaterDirectTopRight,      //左下     ImageWaterDirectBottomLeft,      //右下     ImageWaterDirectBottomRight,      //正中     ImageWaterDirectCenter  }ImageWaterDirect;  #pragma mark - 水印 /**  *  文字水印  *  *  @param text      文字  *  @param direction 文字方向  *  @param fontColor 文字颜色  *  @param fontPoint 字体  *  @param marginXY   对齐点  *  *  @return  */ - (UIImage *)waterWithText:(NSString *)text                  direction:(ImageWaterDirect)direction                  fontColor:(UIColor *)fontColor                  fontPoint:(CGFloat)fontPoint                   marginXY:(CGPoint)marginXY{      CGSize size = self.size;      CGRect rect = (CGRect){CGPointZero,size};      //新建图片图形上下文     UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);      //绘制图片     [self drawInRect:rect];      //绘制文本     NSDictionary *attr =@{NSFontAttributeName : [UIFont systemFontOfSize:fontPoint],NSForegroundColorAttributeName:fontColor};      CGRect strRect = [self calWidth:text attr:attr direction:direction rect:rect marginXY:marginXY];      [text drawInRect:strRect withAttributes:attr];      //获取图片     UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();      //结束图片图形上下文     UIGraphicsEndImageContext();      return newImage; }  /**  *  绘制图片水印  *  *  @param waterImage 图片水印  *  @param direction  方向  *  @param waterSize  水印大小  *  @param marginXY   对齐点  *  *  @return  */ - (UIImage *)waterWithWaterImage:(UIImage *)waterImage                        direction:(ImageWaterDirect)direction                        waterSize:(CGSize)waterSize                         marginXY:(CGPoint)marginXY{      CGSize size = self.size;      CGRect rect = (CGRect){CGPointZero,size};      //新建图片图形上下文     UIGraphicsBeginImageContextWithOptions(size, NO, 0.0f);      //绘制图片     [self drawInRect:rect];      //计算水印的rect     CGSize waterImageSize = CGSizeEqualToSize(waterSize, CGSizeZero)?waterImage.size:waterSize;     CGRect calRect = [self rectWithRect:rect size:waterImageSize direction:direction marginXY:marginXY];      //绘制水印图片     [waterImage drawInRect:calRect];      //获取图片     UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();      //结束图片图形上下文     UIGraphicsEndImageContext();      return newImage; }  /**  *  文字水印位置  *  *  @param str       字符串  *  @param attr      字符串属性  *  @param direction 方向  *  @param rect      图片Rect  *  @param marginXY  对齐点  *  *  @return  */ - (CGRect)calWidth:(NSString *)str               attr:(NSDictionary *)attr          direction:(ImageWaterDirect)direction               rect:(CGRect)rect           marginXY:(CGPoint)marginXY{      CGSize size =  [str sizeWithAttributes:attr];      CGRect calRect = [self rectWithRect:rect size:size direction:direction marginXY:marginXY];      return calRect; }  /**  *  计算水印位置  *  *  @param rect      图片rect  *  @param size      size  *  @param direction 文字方向  *  @param marginXY   对齐点  *  *  @return  */ - (CGRect)rectWithRect:(CGRect)rect                   size:(CGSize)size              direction:(ImageWaterDirect)direction               marginXY:(CGPoint)marginXY{      CGPoint point = CGPointZero;      //右上     if(ImageWaterDirectTopRight == direction) point = CGPointMake(rect.size.width - size.width, 0);      //左下     if(ImageWaterDirectBottomLeft == direction) point = CGPointMake(0, rect.size.height - size.height);      //右下     if(ImageWaterDirectBottomRight == direction) point = CGPointMake(rect.size.width - size.width, rect.size.height - size.height);      //正中     if(ImageWaterDirectCenter == direction) point = CGPointMake((rect.size.width - size.width)*.5f, (rect.size.height - size.height)*.5f);      point.x+=marginXY.x;     point.y+=marginXY.y;      CGRect calRect = (CGRect){point,size};      return calRect; }

GIF动画

  • 播放gif格式的动画
    UIImage 分类大集合
    动画演示.gif

#pragma mark - Gif /**  *  播放动画  *  *  @param data 源文件(图片源)  *  *  @return  */ + (UIImage *)animatedGIFWithData:(NSData *)data {     if (!data) {         return nil;     }      // 加载所有图片     CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);     // 图片数量     size_t count = CGImageSourceGetCount(source);      UIImage *animatedImage;     // 只有一张,直接加载     if (count <= 1) {         animatedImage = [[UIImage alloc] initWithData:data];     }     // 多张图片,循环播放     else {         NSMutableArray *images = [NSMutableArray array];          NSTimeInterval duration = 0.0f;          for (size_t i = 0; i < count; i++) {              CGImageRef image = CGImageSourceCreateImageAtIndex(source, i, NULL);             // 图片播放时间累加             duration += [self frameDurationAtIndex:i source:source];              [images addObject:[UIImage imageWithCGImage:image                                                   scale:[UIScreen mainScreen].scale                                             orientation:UIImageOrientationUp]];              CGImageRelease(image);         }          if (!duration) {             duration = (1.0f / 10.0f) * count;         }         // 加载动画图片,指定动画播放时间         animatedImage = [UIImage animatedImageWithImages:images duration:duration];     }      CFRelease(source);      return animatedImage; }  /**  *  计算动画中每一张图片的播放时间  *  *  @param index  图片索引  *  @param source 图片组  *  *  @return  播放时间  */ + (float)frameDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {     float frameDuration = 0.1f;      // 字典转换     CFDictionaryRef cfFrameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);     NSDictionary *frameProperties = (__bridge NSDictionary *)cfFrameProperties;     NSDictionary *gifProperties = frameProperties[(NSString *)kCGImagePropertyGIFDictionary];      // 如果有延迟时间     NSNumber *delayTimeUnclampedProp = gifProperties[(NSString *)kCGImagePropertyGIFUnclampedDelayTime];     if (delayTimeUnclampedProp) {         frameDuration = [delayTimeUnclampedProp floatValue];     }     // 否则就获取播放下一张图片需要等待的时间     else {          NSNumber *delayTimeProp = gifProperties[(NSString *)kCGImagePropertyGIFDelayTime];         if (delayTimeProp) {             frameDuration = [delayTimeProp floatValue];         }     }      // 设置最小值     if (frameDuration < 0.011f) {         frameDuration = 0.100f;     }      CFRelease(cfFrameProperties);     return frameDuration; }  /**  *  播放gif动画  *  *  @param name 文件名  *  *  @return  */ + (UIImage *)animatedGIFNamed:(NSString *)name {     CGFloat scale = [UIScreen mainScreen].scale;      // 视网膜屏,可能要加载高清图     if (scale > 1.0f) {         // 文件名1         NSString *retinaPath = [[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"gif"];          NSData *data = [NSData dataWithContentsOfFile:retinaPath];          if (data) {             return [UIImage animatedGIFWithData:data];         }          // 文件名2         NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];          data = [NSData dataWithContentsOfFile:path];          if (data) {             return [UIImage animatedGIFWithData:data];         }          return [UIImage imageNamed:name];     }     // 普通屏幕     else {         NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"gif"];          NSData *data = [NSData dataWithContentsOfFile:path];          if (data) {             return [UIImage animatedGIFWithData:data];         }          return [UIImage imageNamed:name];     } }  /**  *  缩放动画  *  *  @param size 大小  *  *  @return    */ - (UIImage *)animatedImageByScalingAndCroppingToSize:(CGSize)size {     if (CGSizeEqualToSize(self.size, size) || CGSizeEqualToSize(size, CGSizeZero)) {         return self;     }      CGSize scaledSize = size;     CGPoint thumbnailPoint = CGPointZero;      CGFloat widthFactor = size.width / self.size.width;     CGFloat heightFactor = size.height / self.size.height;     CGFloat scaleFactor = (widthFactor > heightFactor) ? widthFactor : heightFactor;     scaledSize.width = self.size.width * scaleFactor;     scaledSize.height = self.size.height * scaleFactor;      if (widthFactor > heightFactor) {         thumbnailPoint.y = (size.height - scaledSize.height) * 0.5;     }     else if (widthFactor < heightFactor) {         thumbnailPoint.x = (size.width - scaledSize.width) * 0.5;     }      NSMutableArray *scaledImages = [NSMutableArray array];      // 重绘制图片     UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);     for (UIImage *image in self.images) {         [image drawInRect:CGRectMake(thumbnailPoint.x, thumbnailPoint.y, scaledSize.width, scaledSize.height)];         UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();          [scaledImages addObject:newImage];     }      UIGraphicsEndImageContext();      return [UIImage animatedImageWithImages:scaledImages duration:self.duration]; }

由CIImage生成UIImage

  • 用到CIImage时可能需要转换,直接生成指定尺寸的UIInage
/**  *  根据CIImage生成指定大小的UIImage  *  *  @param image CIImage  *  @param size  图片宽度  */ - (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat) size {     CGRect extent = CGRectIntegral(image.extent);     CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));      // 1.创建bitmap;     size_t width = CGRectGetWidth(extent) * scale;     size_t height = CGRectGetHeight(extent) * scale;     CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();     CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);     CIContext *context = [CIContext contextWithOptions:nil];     CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];     CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);     CGContextScaleCTM(bitmapRef, scale, scale);     CGContextDrawImage(bitmapRef, extent, bitmapImage);      // 2.保存bitmap到图片     CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);     UIImage *resultImage = [UIImage imageWithCGImage:scaledImage];     CGContextRelease(bitmapRef);     CGImageRelease(bitmapImage);     CGColorSpaceRelease(cs);     CGImageRelease(scaledImage);     return resultImage; }

好了,接下来会继续整理相关分类

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » UIImage 分类大集合

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址