简单的图片处理工具:imagetools
头文件 :ImageTool.h
#import <Foundation/Foundation.h>
@interface ImageTool : NSObject
//返回单例的静态方法
+(ImageTool *)shareTool;
//返回特定尺寸的UImage , image参数为原图片,size为要设定的图片大小
-(UIImage*)resizeImageToSize:(CGSize)size
sizeOfImage:(UIImage*)image;
//在指定的视图内进行截屏操作,返回截屏后的图片
-(UIImage *)imageWithScreenContentsInView:(UIView *)view;
/*
*截取指定位置的图片
*r 截取的frame范围
*/
-(UIImage *)imageFromView: (UIView *) theView atFrame:(CGRect)r;
/*
*截取圆形的image
*inset 半径
*/
-(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset;
@end
.m文件 ImageTool.m
#import "ImageTool.h"
#import <QuartzCore/QuartzCore.h>
@implementation ImageTool
static ImageTool *_shareImageTool =nil;
//返回单例的静态方法
+(ImageTool *)shareTool
{
//确保线程安全
@synchronized(self){
//确保只返回一个实例
if (_shareImageTool == nil) {
_shareImageTool = [[ImageTool alloc] init];
}
}
return _shareImageTool;
}
-(id)init
{
self = [super init];
if (self) {
}
return self;
}
//在指定的视图内进行截屏操作,返回截屏后的图片
-(UIImage *)imageWithScreenContentsInView:(UIView *)view
{
//根据屏幕大小,获取上下文
UIGraphicsBeginImageContext([[UIScreen mainScreen] bounds].size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
-(UIImage*)resizeImageToSize:(CGSize)size
sizeOfImage:(UIImage*)image
{
UIGraphicsBeginImageContext(size);
//获取上下文内容
CGContextRef ctx= UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, 0.0, size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
//重绘image
CGContextDrawImage(ctx,CGRectMake(0.0f, 0.0f, size.width, size.height), image.CGImage);
//根据指定的size大小得到新的image
UIImage* scaled= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaled;
}
-(UIImage *)imageFromView: (UIView *) theView atFrame:(CGRect)r
{
UIGraphicsBeginImageContext(theView.frame.size);
CGContextRef context=UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
UIRectClip(r);
[theView.layer renderInContext:context];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
return theImage;//[self getImageAreaFromImage:theImage atFrame:r];
}
-(UIImage*) circleImage:(UIImage*) image withParam:(CGFloat) inset {
UIGraphicsBeginImageContext(image.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2);
CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
CGRect rect = CGRectMake(inset, inset, image.size.width - inset * 2.0f, image.size.height - inset * 2.0f);
CGContextAddEllipseInRect(context, rect);
CGContextClip(context);
[image drawInRect:rect];
CGContextAddEllipseInRect(context, rect);
CGContextStrokePath(context);
UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newimg;
}
@end