如何以编程方式将图像裁剪成碎片 [英] how to crop image in to pieces programmatically
问题描述
我需要以编程方式将图像分成9个部分。有关如何做到这一点的任何建议?
I need to divide an image into 9 pieces programmatically. Any suggestions on how to do this?
推荐答案
下面的代码也是一种解决方案,可以检测被点击的图片。我们的想法是采用UIImage并使用CGImageCreateWithImageInRect来裁剪碎片。从裁剪的部分创建一个新的UIImage并将其放在UIImageView中。为了使轻敲手势起作用,我必须将UIImageView放在UIView中。最后,提供手势和唯一标记,以便在点击时识别该作品。
The code below is also a solution that detects the piece of the picture that was tapped on. The idea is to take a UIImage and use CGImageCreateWithImageInRect to crop out pieces. From the cropped piece create a new UIImage and place it in a UIImageView. In order to get the tap gesture to work I had to place the UIImageView in a UIView. Finally, provide the gesture and a unique tag so that the piece can be identified when tapped on.
- (void)loadView {
UIView* root = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
UIImage* whole = [UIImage imageNamed:@"whole.jpg"]; //I know this image is 300x300
int partId = 0;
for (int x=0; x<=200; x+=100) {
for(int y=0; y<=200; y+=100) {
CGImageRef cgImg = CGImageCreateWithImageInRect(whole.CGImage, CGRectMake(x, y, 100, 100));
UIImage* part = [UIImage imageWithCGImage:cgImg];
UIImageView* iv = [[UIImageView alloc] initWithImage:part];
UIView* sView = [[UIView alloc] initWithFrame:CGRectMake(200-x, 200-y, 100, 100)];
[sView addSubview:iv];
[iv release];
UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(tap:)];
tap.numberOfTapsRequired = 1;
[sView addGestureRecognizer:tap];
[tap release];
sView.tag = partId;
[root addSubview:sView];
[sView release];
partId++;
CGImageRelease(cgImg);
}
}
self.view = root;
}
- (void)tap:(UITapGestureRecognizer*)gesture
{
NSLog(@"image tap=%d", gesture.view.tag);
}
这篇关于如何以编程方式将图像裁剪成碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!