iOS切图

+ (NSDictionary *)SeparateImage:(UIImage *)image ByX:(int)x andY:(int)y cacheQuality:(float)quality {
	if (x < 1) {
		return nil;
	} else if (y < 1) {
		return nil;
	}
	if (![image isKindOfClass:[UIImage class]]) {
		return nil;
	}
    
	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];
	NSString *prefixName = @"win";
	
	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];
			if (quality <= 0)
				continue;
			quality = (quality > 1) ? 1 : quality;
			NSString *_imagePath = [NSHomeDirectory() stringByAppendingPathComponent:_imageString];
			NSData * _imageData = UIImageJPEGRepresentation(elementImage, quality);
			[_imageData writeToFile:_imagePath atomically:NO];
		}
	}
    
	NSDictionary *_dictionary = _mutableDictionary;
	return _dictionary;
}
 

你可能感兴趣的:(ios,iPhone)