图片分割的代码

/*

 +(NSDictionary*)SeparateImage:(UIImage*)image ByX:(int)x andY:(int)y cacheQuality:(float)quality;

 方法说明:

 NSDictionary*:返回字典,UIImageView格式,不仅含有 Image 还含有 Rect

 image: 图片资源,要求为UIImage格式。x: y:分别表示要切成几行和列,最小值为1

 quality:处理后保存的小图片的质量。(01]有效,小于或为0不保存,大于1时会被强强制为1

 切割后的小图片保存位置为 Homedirectory 可以通过 nslog(@"%@",NSHomedirectory()); 查出。

 

 用途:

 适合图片处理应用里为图片添加百叶窗效果,或者拼图游戏里...

 */

 

 

+(NSDictionary*)SeparateImage:(UIImage*)image ByX:(int)x andY:(int)y cacheQuality:(float)quality

{

//kill errors

if (x<1) {

NSLog(@"illegal x!");

return nil;

}else if (y<1) {

NSLog(@"illegal y!");

return nil;

}

if (![image isKindOfClass:[UIImage class]]) {

NSLog(@"illegal image format!");

return nil;

}

//attributes of element

float _xstep=image.size.width*1.0/(y+1);

float _ystep=image.size.height*1.0/(x+1);

NSMutableDictionary*_mutableDictionary=[[[NSMutableDictionary alloc]initWithCapacity:1]autorelease];

//NSArray*_array=[imageName componentsSeparatedByString:@"."];

//NSString*prefixName=[_array objectAtIndex:0];

NSString*prefixName=@"win";

//snap in context and create element image view

for (int i=0; i<x; i++) 

{

for (int j=0; j<y; j++) 

{

CGRect rect=CGRectMake(_xstep*j, _ystep*i, _xstep, _ystep);

CGImageRef imageRef=CGImageCreateWithImageInRect([image CGImage],rect);

UIImage* elementImage=[UIImage imageWithCGImage:imageRef];

UIImageView*_imageView=[[UIImageView alloc] initWithImage:elementImage];

_imageView.frame=rect;

NSString*_imageString=[NSString stringWithFormat:@"%@_%d_%d.jpg",prefixName,i,j];

[_mutableDictionary setObject:_imageView forKey:_imageString];

//CFRelease(imageRef);

if (quality<=0

{

continue;

}

quality=(quality>1)?1:quality;

NSString*_imagePath=[NSHomeDirectory() stringByAppendingPathComponent:_imageString];

NSData* _imageData=UIImageJPEGRepresentation(elementImage, quality);

[_imageData writeToFile:_imagePath atomically:NO];

}

}

//return dictionary including image views

NSDictionary*_dictionary=_mutableDictionary;

return _dictionary;

}

posted @ 2011-06-15 23:04  冷愤僧  阅读(1231)  评论(0编辑  收藏  举报