一有用的 UIImage 扩展,支持(等比例)放大和旋转可在许多 App 中使用。

UIImage-Extensions.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
CGFloat DegreesToRadians(CGFloat degrees); CGFloat RadiansToDegrees(CGFloat radians); @interface UIImage (JQ_Extensions)
- (UIImage *)imageAtRect:(CGRect)rect;- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
- (UIImage *)imageByScalingToSize:(CGSize)targetSize;
- (UIImage *)imageRotatedByRadians:(CGFloat)radians;
- (UIImage *)imageRotatedByDegrees:(CGFloat)degrees; - (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2;
[objc] view plaincopyprint?
- (UIImage *) imageWithBackgroundColor:(UIColor *)bgColor
shadeAlpha1:(CGFloat)alpha1
shadeAlpha2:(CGFloat)alpha2
shadeAlpha3:(CGFloat)alpha3
shadowColor:(UIColor *)shadowColor
shadowOffset:(CGSize)shadowOffset
shadowBlur:(CGFloat)shadowBlur;
- (UIImage *)imageWithShadowColor:(UIColor *)shadowColor
shadowOffset:(CGSize)shadowOffset
shadowBlur:(CGFloat)shadowBlur;<br>
- (UIImage *)imageByApplyingAlpha:(CGFloat)alpha;
- ( void ) saveToAlbumWithMetadata: ( NSDictionary * ) metadata
customAlbumName: ( NSString * ) customAlbumName
completionBlock: ( void ( ^ )( void )) completionBlock
failureBlock: ( void ( ^ )( NSError * error )) failureBlock
@end;
UIImage-Extensions.m #import "UIImage-Extensions.h" CGFloat DegreesToRadians(CGFloat degrees) {return degrees * M_PI / ;};
CGFloat RadiansToDegrees(CGFloat radians) {return radians * /M_PI;}; @implementation UIImage (JQ_Extensions) -(UIImage *)imageAtRect:(CGRect)rect
{ CGImageRef imageRef = CGImageCreateWithImageInRect([self CGImage], rect);
UIImage* subImage = [UIImage imageWithCGImage: imageRef];
CGImageRelease(imageRef); return subImage; }
- (UIImage *)imageByScalingProportionallyToSize:(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;
else
scaleFactor = heightFactor; 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;
}
} // this is actually the interesting part: UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); if(newImage == nil) NSLog(@"could not scale image"); return newImage ;
} - (UIImage *)imageByScalingToSize:(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); // this is actually the interesting part: UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero;
thumbnailRect.origin = thumbnailPoint;
thumbnailRect.size.width = scaledWidth;
thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext(); if(newImage == nil) NSLog(@"could not scale image"); return newImage ;
} - (UIImage *)imageRotatedByRadians:(CGFloat)radians
{
return [self imageRotatedByDegrees:RadiansToDegrees(radians)];
} - (UIImage *)imageRotatedByDegrees:(CGFloat)degrees
{
// calculate the size of the rotated view's containing box for our drawing space
UIView *rotatedViewBox = [[UIView alloc] initWithFrame:CGRectMake(,,self.size.width, self.size.height)];
CGAffineTransform t = CGAffineTransformMakeRotation(DegreesToRadians(degrees));
rotatedViewBox.transform = t;
CGSize rotatedSize = rotatedViewBox.frame.size;
[rotatedViewBox release]; // Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize);
CGContextRef bitmap = UIGraphicsGetCurrentContext(); // Move the origin to the middle of the image so we will rotate and scale around the center.
CGContextTranslateCTM(bitmap, rotatedSize.width/, rotatedSize.height/); // // Rotate the image context
CGContextRotateCTM(bitmap, DegreesToRadians(degrees)); // Now, draw the rotated/scaled image into the context
CGContextScaleCTM(bitmap, 1.0, -1.0);
CGContextDrawImage(bitmap, CGRectMake(-self.size.width / , -self.size.height / , self.size.width, self.size.height), [self CGImage]); UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage; } // Combine two UIImages [objc] view plaincopyprint?
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2 {
UIGraphicsBeginImageContext(image2.size); // Draw image1
[image1 drawInRect:CGRectMake(, , image1.size.width, image1.size.height)]; // Draw image2
[image2 drawInRect:CGRectMake(, , image2.size.width, image2.size.height)]; UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();<br>
return resultingImage;
}
[objc] view plaincopyprint?
- (UIImage *) imageWithBackgroundColor:(UIColor *)bgColor
shadeAlpha1:(CGFloat)alpha1
shadeAlpha2:(CGFloat)alpha2
shadeAlpha3:(CGFloat)alpha3
shadowColor:(UIColor *)shadowColor
shadowOffset:(CGSize)shadowOffset
shadowBlur:(CGFloat)shadowBlur {
UIImage *image = self;
CGColorRef cgColor = [bgColor CGColor];
CGColorRef cgShadowColor = [shadowColor CGColor];
CGFloat components[] = {,,,alpha1,,,,alpha1,,,,alpha2,,,,alpha3};
CGFloat locations[] = {,0.5,0.6,};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef colorGradient = CGGradientCreateWithColorComponents(colorSpace, components, locations, (size_t));
CGRect contextRect;
contextRect.origin.x = 0.0f;
contextRect.origin.y = 0.0f;
contextRect.size = [image size];
//contextRect.size = CGSizeMake([image size].width+5,[image size].height+5);
// Retrieve source image and begin image context
UIImage *itemImage = image;
CGSize itemImageSize = [itemImage size];
CGPoint itemImagePosition;
itemImagePosition.x = ceilf((contextRect.size.width - itemImageSize.width) / );
itemImagePosition.y = ceilf((contextRect.size.height - itemImageSize.height) / );
UIGraphicsBeginImageContext(contextRect.size);
CGContextRef c = UIGraphicsGetCurrentContext();
// Setup shadow
CGContextSetShadowWithColor(c, shadowOffset, shadowBlur, cgShadowColor);
// Setup transparency layer and clip to mask
CGContextBeginTransparencyLayer(c, NULL);
CGContextScaleCTM(c, 1.0, -1.0);
CGContextClipToMask(c, CGRectMake(itemImagePosition.x, -itemImagePosition.y, itemImageSize.width, -itemImageSize.height), [itemImage CGImage]);
// Fill and end the transparency layer
CGContextSetFillColorWithColor(c, cgColor);
contextRect.size.height = -contextRect.size.height;
CGContextFillRect(c, contextRect);
CGContextDrawLinearGradient(c, colorGradient,CGPointZero,CGPointMake(contextRect.size.width*1.0/4.0,contextRect.size.height),);
CGContextEndTransparencyLayer(c);
//CGPointMake(contextRect.size.width*3.0/4.0, 0)
// Set selected image and end context
UIImage *resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGColorSpaceRelease(colorSpace);
CGGradientRelease(colorGradient);
return resultImage;
} - (UIImage *)imageWithShadowColor:(UIColor *)shadowColor
shadowOffset:(CGSize)shadowOffset
shadowBlur:(CGFloat)shadowBlur
{
CGColorRef cgShadowColor = [shadowColor CGColor];
CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
CGContextRef shadowContext = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
CGImageGetBitsPerComponent(self.CGImage), ,
colourSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colourSpace); // Setup shadow
CGContextSetShadowWithColor(shadowContext, shadowOffset, shadowBlur, cgShadowColor);
CGRect drawRect = CGRectMake(-shadowBlur, -shadowBlur, self.size.width + shadowBlur, self.size.height + shadowBlur);
CGContextDrawImage(shadowContext, drawRect, self.CGImage); CGImageRef shadowedCGImage = CGBitmapContextCreateImage(shadowContext);
CGContextRelease(shadowContext); UIImage * shadowedImage = [UIImage imageWithCGImage:shadowedCGImage];
CGImageRelease(shadowedCGImage); return shadowedImage;
} - (UIImage *)imageByApplyingAlpha:(CGFloat)alpha {
UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0f); CGContextRef ctx = UIGraphicsGetCurrentContext();
CGRect area = CGRectMake(, , self.size.width, self.size.height); CGContextScaleCTM(ctx, , -);
CGContextTranslateCTM(ctx, , -area.size.height); CGContextSetBlendMode(ctx, kCGBlendModeMultiply); CGContextSetAlpha(ctx, alpha); CGContextDrawImage(ctx, area, self.CGImage); UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return newImage;
} - ( void ) saveToAlbumWithMetadata: ( NSDictionary * ) metadata
customAlbumName: ( NSString * ) customAlbumName
completionBlock: ( void ( ^ )( void )) completionBlock
failureBlock: ( void ( ^ )( NSError * error )) failureBlock
{
NSData * imageData = UIImagePNGRepresentation ( self );
ALAssetsLibrary * assetsLibrary = [[ ALAssetsLibrary alloc ] init ];
void ( ^ AddAsset )( ALAssetsLibrary * , NSURL * ) = ^ ( ALAssetsLibrary * assetsLibrary , NSURL * assetURL ) {
[ assetsLibrary assetForURL : assetURL resultBlock :^ ( ALAsset * asset ) {
[ assetsLibrary enumerateGroupsWithTypes : ALAssetsGroupAll usingBlock :^ ( ALAssetsGroup * group , BOOL * stop ) {
if ([[ group valueForProperty : ALAssetsGroupPropertyName ] isEqualToString : customAlbumName ]) {
[ group addAsset : asset ];
if ( completionBlock ) {
completionBlock ();
}
}
} failureBlock :^ ( NSError * error ) {
if ( failureBlock ) {
failureBlock ( error );
}
}];
} failureBlock :^ ( NSError * error ) {
if ( failureBlock ) {
failureBlock ( error );
}
}];
};
[ assetsLibrary writeImageDataToSavedPhotosAlbum : imageData metadata : metadata completionBlock :^ ( NSURL * assetURL , NSError * error ) {
if ( customAlbumName ) {
[ assetsLibrary addAssetsGroupAlbumWithName : customAlbumName resultBlock :^ ( ALAssetsGroup * group ) {
if ( group ) {
[ assetsLibrary assetForURL : assetURL resultBlock :^ ( ALAsset * asset ) {
[ group addAsset : asset ];
if ( completionBlock ) {
completionBlock ();
}
} failureBlock :^ ( NSError * error ) {
if ( failureBlock ) {
failureBlock ( error );
}
}];
} else {
AddAsset ( assetsLibrary , assetURL );
}
} failureBlock :^ ( NSError * error ) {
AddAsset ( assetsLibrary , assetURL );
}];
} else {
if ( completionBlock ) {
completionBlock ();
}
}
}];
}
@end;

iOS UIImage扩展方法(category):放大、旋转、合并UIImage、增加渐变层、添加阴影、调节透明度、保存到相册的更多相关文章

  1. IOS中扩展机制Category和associative

    在ios开发中,有时候会遇到以下的问题,需要在一个类中添加自己的一些属性和方法.一般的做法是重写一个类来继承它,但是有时候就只是需要添加一些简单的属性和方法,那么这样做就显得过于麻烦,其实在IOS中还 ...

  2. iOS图片折叠效果:Layer的contentsRect属性和渐变层

    http://www.cocoachina.com/ios/20150722/12622.html 作者:@吖了个峥 授权本站转载. 前言 此次文章,讲述的是Layer的一个属性contentsRec ...

  3. C#中扩展方法

    什么是扩展方法? 扩展方法顾名思义,就是允许向现有的“类型”添加方法,而无需创建派生类.重新编译或以其他方式修改原来类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用. 扩 ...

  4. Extension Methods(扩展方法)

    在 OOPL 中,有静态方法.实例方法和虚方法,如下:   public sealed class String {      public static bool  IsNullOrEmpty(st ...

  5. JS 扩展方法prototype

    通过类对象的prototype设置扩展方法,下面为String对象增加quote(两边加字符)方法 <script type="text/javascript"> St ...

  6. iOS 拍照保存到相册

    之前看了一些开源的代码,里面有一个功能,就是将图片下载到相册,仔细看了其中的代码,只有很简单的一句话,并且保存过后,还可以判断是否保存成功. 如下代码所示, 点击按钮,将self.imageView上 ...

  7. iOS学习系列 - 扩展机制category与associative

    iOS学习系列 - 扩展机制category与associative category与associative作为objective-c的扩展机制的两个特性,category即类型,可以通过它来扩展方 ...

  8. UIImage扩展用代码直接改变图片大小

    以下内容属于转载 在iOS中,uiimage没有用于修改大小的属性,要在代码中改变uiimage图片的大小,需要扩展UIImage类,如下: 头文件: #import<UIKit/UIKit.h ...

  9. 扩展方法以及LinQ的学习

    我们今天学习的内容其实还是蛮多的,学习了自动属性,扩展方法,复习初始化器,以及LinQ的一些方法,其实感觉有些还是很熟悉的,在前面的学习过程中有时间感觉学习的知识知道了怎么使用,但是还没有在项目中使用 ...

随机推荐

  1. js原生封装自定义滚动条

    /* * @Author: dothin前端 * @Date: 2015-11-21 00:12:15 * @Last Modified by: dothin前端 * @Last Modified t ...

  2. C#错误异常列表

    Exception: 所有异常对象的基类. SystemException:运行时产生的所有错误的基类. IndexOutOfRangeException:当一个数组的下标超出范围时运行时引发. Nu ...

  3. JavaScript Unicode字符操作

    charCodeAt() 方法 定义和用法charCodeAt() 方法可返回指定位置的字符的 Unicode 编码.这个返回值是 0 - 65535 之间的整数.方法 charCodeAt() 与 ...

  4. HTML之Data URL(转)

    Data URL给了我们一种很巧妙的将图片“嵌入”到HTML中的方法.跟传统的用img标记将服务器上的图片引用到页面中的方式不一样,在Data URL协议中,图片被转换成base64编码的字符串形式, ...

  5. 动态插入图片到 svg 中

    动态插入图片到 svg 中使用 createElementNS 来创建svg标签,通过setAttributeNS 来设置属性, 要注意两点,创建的时候要有'http://www.w3.org/200 ...

  6. 46 Permutations(全排列Medium)

    题目意思:全排列 思路:其实看这题目意思,是不太希望用递归的,不过还是用了递归,非递归的以后再搞吧 ps:vector这玩意不能随便返回,开始递归方法用vector,直接到500ms,换成void,到 ...

  7. 解决css3遮罩层挡住下面元素事件的方法

    比如大家常看到的鼠标移入图片中,会有一个挡住图片的黑色半透明遮罩层,上面还有文字介绍,这时候就会遇到该层遮挡住下面图片的跳转链接事件,这时候怎么办呢?有个简单的css3属性可以快速解决该问题:poin ...

  8. 如何用angularjs制作一个完整的表格之二__表格分页功能

    接上一次,这次主要介绍表格分页功能,由于项目需要这个案例是关于前端分页的方式,现在很少会这么用了,但如有需要可以参考其中的思路 html: 1.通过UL来展示页标,其中每个页标的li是通过异步加载从获 ...

  9. GFStableList Adapter

    STL中,list的优点是插入.删除性能极佳(时间复杂度只需O(1)即可),而且非常重要的在删除节点后,其迭代器不失效,但list查找却不擅长.map由于其实现的数据结构为rb-tree,因此,其插入 ...

  10. 习题二:string数组应用

    说明: 读字符串char buf[100]="xxx:yyy:zzz:aaa:bbb" 按“:”进行分解到string数组中去 逻辑: 通过指针遍历整个字符串 遇到'\0'表示字符 ...