123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688 |
- //
- // UIImage+Extension.m
- // HuaKaiChat
- //
- // Created by BigBiao on 2017/9/16.
- // Copyright © 2017年 huakai. All rights reserved.
- //
- #import "UIImage+Extension.h"
- #import <AVFoundation/AVFoundation.h>
- #import <Accelerate/Accelerate.h>
- #import <float.h>
- #define AspectRatio 1.0
- #define AspectRatioDT 1.0
- @implementation UIImage (Extension)
- - (UIImage*)imageWithSize:(CGSize)size cornerRadius:(CGFloat)corner rectCornerType:(UIRectCorner)cornerType{
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(size, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContext(size);
- if (!UIGraphicsGetCurrentContext()) {
- return nil;
- }
- UIBezierPath* path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, size.width, size.height) byRoundingCorners:cornerType cornerRadii:CGSizeMake(corner, corner)];
- [path addClip];
- [(UIImage*)self drawInRect:CGRectMake(0, 0, size.width, size.height)];
- UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
- return newImage;
- }
- + (UIImage *)screenshot
- {
-
- CGSize imageSize = [[UIScreen mainScreen] bounds].size;
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(imageSize, CGSizeZero)) {
- return nil;
- }
- if (NULL != UIGraphicsBeginImageContextWithOptions) {
- UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
- } else {
- UIGraphicsBeginImageContext(imageSize);
- }
-
- CGContextRef context = UIGraphicsGetCurrentContext();
-
- for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
- if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
- CGContextSaveGState(context);
-
- CGContextTranslateCTM(context, [window center].x, [window center].y);
-
- CGContextConcatCTM(context, [window transform]);
-
- CGContextTranslateCTM(context,
- -[window bounds].size.width * [[window layer] anchorPoint].x,
- -[window bounds].size.height * [[window layer] anchorPoint].y);
-
- [[window layer] renderInContext:context];
-
- CGContextRestoreGState(context);
- }
- }
- UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
-
- UIGraphicsEndImageContext();
-
- return image;
- }
- + (UIImage *)cutImage:(UIImage*)image isDT:(BOOL)flag
- {
- //压缩图片
- CGSize newSize;
- CGFloat padHeight;
- CGImageRef imageRef = nil;
- newSize.width = image.size.width;
- if (flag) {
- newSize.height = newSize.width*AspectRatioDT;
- padHeight = (image.size.height-image.size.width*AspectRatioDT)/2;
- }else{
- newSize.height = newSize.width*AspectRatio;
- padHeight = (image.size.height-image.size.width*AspectRatio)/2;
- }
-
- imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(0, padHeight, newSize.width, newSize.height));
-
- return [UIImage imageWithCGImage:imageRef];
- }
- + (UIImage *)imageWithVideo:(NSURL *)videoURL
- {
- AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
-
- AVAssetImageGenerator* gen = [[AVAssetImageGenerator alloc] initWithAsset: asset];
-
- gen.appliesPreferredTrackTransform = YES;
- gen.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;
-
- CMTime time = CMTimeMake(0, 2);
-
- NSError *error = nil;
-
- CMTime actualTime;
-
- CGImageRef image = [gen copyCGImageAtTime: time actualTime: &actualTime error:&error];
-
- UIImage *thumb = [[UIImage alloc] initWithCGImage: image];
-
- CGImageRelease(image);
-
- return thumb;
-
- }
- + (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size
- {
- CGRect rect = CGRectMake(0, 0, size.width, size.height);
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(rect.size, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContext(rect.size);
- CGContextRef context = UIGraphicsGetCurrentContext();
- CGContextSetFillColorWithColor(context,color.CGColor);
- CGContextFillRect(context, rect);
- UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
- return img;
- }
- - (UIImage *)imageByApplyingAlpha:(CGFloat)alpha{
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(self.size, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f);
- CGContextRef ctx = UIGraphicsGetCurrentContext();
- CGRect area = CGRectMake(0, 0, self.size.width, self.size.height);
- CGContextScaleCTM(ctx, 1, -1);
- CGContextTranslateCTM(ctx, 0, -area.size.height);
- CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
- CGContextSetAlpha(ctx, alpha);
- CGContextDrawImage(ctx, area, self.CGImage);
- UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return newImage;
-
- }
- + (instancetype)waterImageWithBg:(UIImage*)bgImg centerImg:(NSString *)centerImg
- {
- UIGraphicsBeginImageContextWithOptions(CGSizeMake((KScreenWidth-20)/2, (KScreenWidth-20)/2), NO, 0.0);
- [bgImg drawInRect:CGRectMake(0, 0,(KScreenWidth-20)/2, (KScreenWidth-20)/2)];
-
- //要绘制的内容
- //1.绘制灰色背景
- UIImage* grayImage = [UIImage imageWithColor:DecColorFromRGBA(0, 0, 0,0) size:bgImg.size];
- [grayImage drawInRect:CGRectMake(0, 0, (KScreenWidth-20)/2, (KScreenWidth-20)/2)];
- //2.绘制文字
- // NSString* str =@"免费现场预览";
- // [str drawInRect:CGRectMake(KScreenWidth/3,KScreenWidth*AspectRatio/2-10 ,KScreenWidth/3-30, 40) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15],NSForegroundColorAttributeName:[UIColor whiteColor]}];
- //3.绘制播放按钮
- UIImage* img = [[UIImage imageNamed:centerImg] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
- // [img drawInRect:CGRectMake((KScreenWidth-img.size.width)/2,KScreenWidth*AspectRatio/2-15,img.size.width,img.size.height )];
- [img drawAtPoint:CGPointMake((KScreenWidth-20)/4-img.size.width/2, (KScreenWidth-20)/4-img.size.height/2)];
- // [img drawInRect:CGRectMake(0, 0, img.size.width, img.size.height)];
-
- UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return newImage;
- }
- + (UIImage*)screenView:(UIView *)view{
- CGRect rect = view.frame;
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(rect.size, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContext(rect.size);
- CGContextRef context = UIGraphicsGetCurrentContext();
- [view.layer renderInContext:context];
- //add by leo
- [view drawViewHierarchyInRect: view.frame afterScreenUpdates:YES];
- UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return img;
- }
- //图片压缩到指定大小1280*1280内
- - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize
- {
- UIImage *sourceImage = self;
- UIImage *newImage = nil;
- CGSize imageSize = sourceImage.size;
- CGFloat width = imageSize.width;
- CGFloat height = imageSize.height;
- CGFloat targetWidth = targetSize.width;
- CGFloat targetHeight = targetSize.height;
- CGFloat scaleFactor = 0.0;
- CGFloat scaledWidth = targetWidth;
- CGFloat scaledHeight = targetHeight;
- CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
-
- if (CGSizeEqualToSize(imageSize, targetSize) == NO)
- {
- CGFloat widthFactor = targetWidth / width;
- CGFloat heightFactor = targetHeight / height;
-
- if (widthFactor > heightFactor)
- scaleFactor = widthFactor; // scale to fit height
- else
- scaleFactor = heightFactor; // scale to fit width
- scaledWidth= width * scaleFactor;
- scaledHeight = height * scaleFactor;
-
- // center the image
- if (widthFactor > heightFactor)
- {
- thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
- }
- else if (widthFactor < heightFactor)
- {
- thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
- }
- }
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(targetSize, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContext(targetSize); // this will crop
-
- CGRect thumbnailRect = CGRectZero;
- thumbnailRect.origin = thumbnailPoint;
- thumbnailRect.size.width= scaledWidth;
- thumbnailRect.size.height = scaledHeight;
-
- [sourceImage drawInRect:thumbnailRect];
-
- newImage = UIGraphicsGetImageFromCurrentImageContext();
- if(newImage == nil)
- NSLog(@"could not scale image");
-
- //pop the context to get back to the default
- UIGraphicsEndImageContext();
- return newImage;
- }
- //循环压缩图片到制定大小
- //循环压缩图片到制定大小
- - (NSData *)compressImageToMaxFileSize:(NSInteger)maxFileSize {
- CGFloat compression = 1.0f;
- CGFloat maxCompression = 0.01f;
- NSData *imageData = UIImageJPEGRepresentation(self, compression);
- NSLog(@"%lu",imageData.length);
- while ([imageData length] > maxFileSize && compression > maxCompression) {
- compression -= 0.01;
- imageData = UIImageJPEGRepresentation(self, compression);
- }
-
- return imageData;
- }
- + (NSData *)zipGiFWithAsset:(PHAsset*)asset{
- NSArray *resourceList = [PHAssetResource assetResourcesForAsset:asset];
- [resourceList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
- PHAssetResource *resource = obj;
- PHAssetResourceRequestOptions *option = [[PHAssetResourceRequestOptions alloc]init];
- option.networkAccessAllowed = YES;
- if ([resource.uniformTypeIdentifier isEqualToString:@"com.compuserve.gif"]) {
- NSLog(@"gif大爷");
- // 首先,需要获取沙盒路径
- NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
- // 拼接图片名为resource.originalFilename的路径
- NSString *imageFilePath = [path stringByAppendingPathComponent:resource.originalFilename];
- __block NSData *data = [[NSData alloc]init];
- [[PHAssetResourceManager defaultManager] writeDataForAssetResource:resource toFile:[NSURL fileURLWithPath:imageFilePath] options:option completionHandler:^(NSError * _Nullable error) {
- if (error) {
- NSLog(@"error:%@",error);
- if(error.code == -1){//文件已存在
- data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:imageFilePath]];
- }
- //NSLog(@"data%@",data);
-
- } else {
- data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:imageFilePath]];
- //NSLog(@"data%@",data);
- }
- }];
-
- }else{
- NSLog(@"jepg大爷");
- }
- }];
- return nil;
- }
- + (NSData *)zipGIFWithData:(NSData *)data {
- // if (!data) {
- // return nil;
- // }
- // CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
- // size_t count = CGImageSourceGetCount(source);
- // UIImage *animatedImage = nil;
- // 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];
- // UIImage *ima = [UIImage imageWithCGImage:image scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
- // ima = [ima zip];
- // [images addObject:ima];
- // CGImageRelease(image);
- // if (!duration) {
- // duration = (1.0f / 10.0f) * count;
- // }
- // animatedImage = [UIImage animatedImageWithImages:images duration:duration];
- // }
- // CFRelease(source);
- // return UIImagePNGRepresentation(animatedImage);
- return nil;
- }
- +(NSData *)zipNSDataWithImage:(UIImage *)sourceImage maxFileSize:(NSInteger)maxFileSize {
- //进行图像尺寸的压缩
- CGSize imageSize = sourceImage.size;//取出要压缩的image尺寸
- CGFloat width = imageSize.width; //图片宽度
- CGFloat height = imageSize.height; //图片高度
- //1.宽高大于1280(宽高比不按照2来算,按照1来算)
- if (width>1280) {
- if (width>height) {
- CGFloat scale = width/height;
- height = 1280;
- width = height*scale;
- }else{
- CGFloat scale = height/width;
- width = 1280;
- height = width*scale;
- }
- //2.高度大于1280
- }else if(height>1280){
- CGFloat scale = height/width;
- width = 1280;
- height = width*scale;
- }else{
- }
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(imageSize, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContext(CGSizeMake(width, height));
- if (sourceImage) {
- [sourceImage drawInRect:CGRectMake(0,0,width,height)];
- }
- UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
- return [newImage compressImageToMaxFileSize:maxFileSize];//200KB
-
- }
- @end
- @implementation UIImage (ImageEffects)
- - (UIImage *)applyLightEffect
- {
- UIColor *tintColor = [UIColor colorWithWhite:1.0 alpha:0.3];
- return [self applyBlurWithRadius:30 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
- }
- - (UIImage *)applyExtraLightEffect
- {
- UIColor *tintColor = [UIColor colorWithWhite:0.97 alpha:0.82];
- return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
- }
- - (UIImage *)applyDarkEffect
- {
- UIColor *tintColor = DecColorFromRGBA(79, 66, 81, 0.8);
- return [self applyBlurWithRadius:20 tintColor:tintColor saturationDeltaFactor:1.8 maskImage:nil];
- }
- - (UIImage *)applyTintEffectWithColor:(UIColor *)tintColor
- {
- const CGFloat EffectColorAlpha = 0.6;
- UIColor *effectColor = tintColor;
- long int componentCount = CGColorGetNumberOfComponents(tintColor.CGColor);
- if (componentCount == 2) {
- CGFloat b;
- if ([tintColor getWhite:&b alpha:NULL]) {
- effectColor = [UIColor colorWithWhite:b alpha:EffectColorAlpha];
- }
- }
- else {
- CGFloat r, g, b;
- if ([tintColor getRed:&r green:&g blue:&b alpha:NULL]) {
- effectColor = [UIColor colorWithRed:r green:g blue:b alpha:EffectColorAlpha];
- }
- }
- return [self applyBlurWithRadius:10 tintColor:effectColor saturationDeltaFactor:-1.0 maskImage:nil];
- }
- - (UIImage *)applyBlurWithRadius:(CGFloat)blurRadius tintColor:(UIColor *)tintColor saturationDeltaFactor:(CGFloat)saturationDeltaFactor maskImage:(UIImage *)maskImage
- {
- // Check pre-conditions.
- if (self.size.width < 1 || self.size.height < 1) {
- NSLog (@"*** error: invalid size: (%.2f x %.2f). Both dimensions must be >= 1: %@", self.size.width, self.size.height, self);
- return nil;
- }
- if (!self.CGImage) {
- NSLog (@"*** error: image must be backed by a CGImage: %@", self);
- return nil;
- }
- if (maskImage && !maskImage.CGImage) {
- NSLog (@"*** error: maskImage must be backed by a CGImage: %@", maskImage);
- return nil;
- }
-
- CGRect imageRect = { CGPointZero, self.size };
- UIImage *effectImage = self;
-
- BOOL hasBlur = blurRadius > __FLT_EPSILON__;
- BOOL hasSaturationChange = fabs(saturationDeltaFactor - 1.) > __FLT_EPSILON__;
- if (hasBlur || hasSaturationChange) {
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(self.size, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
- CGContextRef effectInContext = UIGraphicsGetCurrentContext();
- CGContextScaleCTM(effectInContext, 1.0, -1.0);
- CGContextTranslateCTM(effectInContext, 0, -self.size.height);
- CGContextDrawImage(effectInContext, imageRect, self.CGImage);
-
- vImage_Buffer effectInBuffer;
- effectInBuffer.data = CGBitmapContextGetData(effectInContext);
- effectInBuffer.width = CGBitmapContextGetWidth(effectInContext);
- effectInBuffer.height = CGBitmapContextGetHeight(effectInContext);
- effectInBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectInContext);
-
- UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
- CGContextRef effectOutContext = UIGraphicsGetCurrentContext();
- vImage_Buffer effectOutBuffer;
- effectOutBuffer.data = CGBitmapContextGetData(effectOutContext);
- effectOutBuffer.width = CGBitmapContextGetWidth(effectOutContext);
- effectOutBuffer.height = CGBitmapContextGetHeight(effectOutContext);
- effectOutBuffer.rowBytes = CGBitmapContextGetBytesPerRow(effectOutContext);
-
- if (hasBlur) {
- // A description of how to compute the box kernel width from the Gaussian
- // radius (aka standard deviation) appears in the SVG spec:
- // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
- //
- // For larger values of 's' (s >= 2.0), an approximation can be used: Three
- // successive box-blurs build a piece-wise quadratic convolution kernel, which
- // approximates the Gaussian kernel to within roughly 3%.
- //
- // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
- //
- // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
- //
- CGFloat inputRadius = blurRadius * [[UIScreen mainScreen] scale];
- int radius = floor(inputRadius * 3. * sqrt(2 * M_PI) / 4 + 0.5);
- if (radius % 2 != 1) {
- radius += 1; // force radius to be odd so that the three box-blur methodology works.
- }
- vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
- vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
- vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend);
- }
- BOOL effectImageBuffersAreSwapped = NO;
- if (hasSaturationChange) {
- CGFloat s = saturationDeltaFactor;
- CGFloat floatingPointSaturationMatrix[] = {
- 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
- 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
- 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
- 0, 0, 0, 1,
- };
- const int32_t divisor = 256;
- NSUInteger matrixSize = sizeof(floatingPointSaturationMatrix)/sizeof(floatingPointSaturationMatrix[0]);
- int16_t saturationMatrix[matrixSize];
- for (NSUInteger i = 0; i < matrixSize; ++i) {
- saturationMatrix[i] = (int16_t)roundf(floatingPointSaturationMatrix[i] * divisor);
- }
- if (hasBlur) {
- vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
- effectImageBuffersAreSwapped = YES;
- }
- else {
- vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);
- }
- }
- if (!effectImageBuffersAreSwapped)
- effectImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
- if (effectImageBuffersAreSwapped)
- effectImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- }
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(self.size, CGSizeZero)) {
- return nil;
- }
- // Set up output context.
- UIGraphicsBeginImageContextWithOptions(self.size, NO, [[UIScreen mainScreen] scale]);
- CGContextRef outputContext = UIGraphicsGetCurrentContext();
- CGContextScaleCTM(outputContext, 1.0, -1.0);
- CGContextTranslateCTM(outputContext, 0, -self.size.height);
-
- // Draw base image.
- CGContextDrawImage(outputContext, imageRect, self.CGImage);
-
- // Draw effect image.
- if (hasBlur) {
- CGContextSaveGState(outputContext);
- if (maskImage) {
- CGContextClipToMask(outputContext, imageRect, maskImage.CGImage);
- }
- CGContextDrawImage(outputContext, imageRect, effectImage.CGImage);
- CGContextRestoreGState(outputContext);
- }
-
- // Add in color tint.
- if (tintColor) {
- CGContextSaveGState(outputContext);
- CGContextSetFillColorWithColor(outputContext, tintColor.CGColor);
- CGContextFillRect(outputContext, imageRect);
- CGContextRestoreGState(outputContext);
- }
-
- // Output image is ready.
- UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
- return outputImage;
- }
- + (UIImage *)imageWithScreenshot
- {
- NSData *imageData = [self dataWithScreenshotInPNGFormat];
- return [UIImage imageWithData:imageData];
- }
- + (NSData *)dataWithScreenshotInPNGFormat
- {
- CGSize imageSize = CGSizeZero;
- UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
- if (UIInterfaceOrientationIsPortrait(orientation))
- imageSize = [UIScreen mainScreen].bounds.size;
- else
- imageSize = CGSizeMake([UIScreen mainScreen].bounds.size.height, [UIScreen mainScreen].bounds.size.width);
-
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(imageSize, CGSizeZero)) {
- return nil;
- }
- UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
- CGContextRef context = UIGraphicsGetCurrentContext();
- for (UIWindow *window in [[UIApplication sharedApplication] windows])
- {
- CGContextSaveGState(context);
- CGContextTranslateCTM(context, window.center.x, window.center.y);
- CGContextConcatCTM(context, window.transform);
- CGContextTranslateCTM(context, -window.bounds.size.width * window.layer.anchorPoint.x, -window.bounds.size.height * window.layer.anchorPoint.y);
- if (orientation == UIInterfaceOrientationLandscapeLeft)
- {
- CGContextRotateCTM(context, M_PI_2);
- CGContextTranslateCTM(context, 0, -imageSize.width);
- }
- else if (orientation == UIInterfaceOrientationLandscapeRight)
- {
- CGContextRotateCTM(context, -M_PI_2);
- CGContextTranslateCTM(context, -imageSize.height, 0);
- } else if (orientation == UIInterfaceOrientationPortraitUpsideDown) {
- CGContextRotateCTM(context, M_PI);
- CGContextTranslateCTM(context, -imageSize.width, -imageSize.height);
- }
- if ([window respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
- {
- [window drawViewHierarchyInRect:window.bounds afterScreenUpdates:YES];
- }
- else
- {
- [window.layer renderInContext:context];
- }
- CGContextRestoreGState(context);
- }
-
- UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
-
- return UIImagePNGRepresentation(image);
- }
- - (UIImage *)cutCircleImage {
- // 传入的View.frame.size是0的话,直接返回nil,防止 UIGraphicsBeginImageContext() 传入0,导致崩溃
- if (CGSizeEqualToSize(self.size, CGSizeZero)) {
- return nil;
- }
- //开始图片上下文
- UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
- // 获取上下文
- CGContextRef ctr = UIGraphicsGetCurrentContext();
- // 设置圆形
- CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
- CGContextAddEllipseInRect(ctr, rect);
- // 裁剪
- CGContextClip(ctr);
- // 将图片画上去
- [self drawInRect:rect];
- UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
- UIGraphicsEndImageContext();
- return image;
- }
- +(UIImage *)boxblurImage:(UIImage *)image withBlurNumber:(CGFloat)blur {
- if (blur < 0.f || blur > 1.f) {
- blur = 0.5f;
- }
- int boxSize = (int)(blur * 40);
- boxSize = boxSize - (boxSize % 2) + 1;
-
- CGImageRef img = image.CGImage;
-
- vImage_Buffer inBuffer, outBuffer;
- vImage_Error error;
-
- void *pixelBuffer;
- //从CGImage中获取数据
- CGDataProviderRef inProvider = CGImageGetDataProvider(img);
- CFDataRef inBitmapData = CGDataProviderCopyData(inProvider);
- //设置从CGImage获取对象的属性
- inBuffer.width = CGImageGetWidth(img);
- inBuffer.height = CGImageGetHeight(img);
- inBuffer.rowBytes = CGImageGetBytesPerRow(img);
-
- inBuffer.data = (void*)CFDataGetBytePtr(inBitmapData);
-
- pixelBuffer = malloc(CGImageGetBytesPerRow(img) *
- CGImageGetHeight(img));
-
- if(pixelBuffer == NULL)
- NSLog(@"No pixelbuffer");
-
- outBuffer.data = pixelBuffer;
- outBuffer.width = CGImageGetWidth(img);
- outBuffer.height = CGImageGetHeight(img);
- outBuffer.rowBytes = CGImageGetBytesPerRow(img);
-
- error = vImageBoxConvolve_ARGB8888(&inBuffer, &outBuffer, NULL, 0, 0, boxSize, boxSize, NULL, kvImageEdgeExtend);
-
- if (error) {
- NSLog(@"error from convolution %ld", error);
- }
-
- CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
- CGContextRef ctx = CGBitmapContextCreate(
- outBuffer.data,
- outBuffer.width,
- outBuffer.height,
- 8,
- outBuffer.rowBytes,
- colorSpace,
- kCGImageAlphaNoneSkipLast);
- CGImageRef imageRef = CGBitmapContextCreateImage (ctx);
- UIImage *returnImage = [UIImage imageWithCGImage:imageRef];
-
- //clean up
- CGContextRelease(ctx);
- CGColorSpaceRelease(colorSpace);
-
- free(pixelBuffer);
- CFRelease(inBitmapData);
-
- CGColorSpaceRelease(colorSpace);
- CGImageRelease(imageRef);
-
- return returnImage;
- }
- @end
|