这可能不像我想象的那么难,但我如何选择图像的一部分?请考虑以下示例:
alt text http://img683.imageshack.us/img683/2680/imagepart.jpg
灰色区域是PNG或JPG格式的图像,现在我想从中选择红色的80x80像素区域。应显示红色区域,其余不显示。我尝试了很多方法:
我也看了一下绘图功能,但我还没有使用它们,这对我来说似乎有点牵强。有什么明显的方法可以做我想做的事情,我错过了吗?我不希望图像被调整大小,只是剪裁。
谢谢你的时间!
答案 0 :(得分:7)
从this问题中窃取下面的代码并查找HitScan的答案。
CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
// or use the UIImage wherever you like
[UIImageView setImage:[UIImage imageWithCGImage:imageRef]];
CGImageRelease(imageRef);
答案 1 :(得分:4)
如果您只想显示图像的中心,则UIImageView
通过IB将内容模式设置为“Aspect Fill”。这将使它居中并裁掉任何额外的东西。
或代码
myImageView.contentMode = UIViewContentModeScaleAspectFill;
答案 2 :(得分:3)
myImageView.contentMode = UIViewContentModeCenter;
myImageView.clipsToBounds = YES;
答案 3 :(得分:1)
请参阅下面的代码。在这里,我提供了一个imageview,并在两个相同的图像视图中将它们分开。
- (void)splitImageView:(UIImageView*)imgView{
UIImage *image = imgView.image;
CGRect rectForDrawing = CGRectMake(0, 0, imgView.frame.size.width/2, imgView.frame.size.height);
CGRect leftRect = CGRectMake(0, 0, imgView.frame.size.width/2, imgView.frame.size.height);
CGRect rightRect = CGRectMake(imgView.frame.size.width/2, 0, imgView.frame.size.width/2, imgView.frame.size.height);
CGImageRef leftReference = CGImageCreateWithImageInRect([image CGImage], leftRect);
CGImageRef rightReference = CGImageCreateWithImageInRect([image CGImage], rightRect);
UIGraphicsBeginImageContextWithOptions(rectForDrawing.size, NO, 0);
CGContextRef con = UIGraphicsGetCurrentContext();
CGContextDrawImage(con, rectForDrawing,flip(leftReference));
imgViewLeft = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()];
imgViewLeft.frame = CGRectMake(imgView.frame.origin.x, imgView.frame.origin.y,
imgView.frame.size.width/2, imgView.frame.size.height);
CGContextDrawImage(con, rectForDrawing,flip(rightReference));
imgViewRight = [[UIImageView alloc] initWithImage:UIGraphicsGetImageFromCurrentImageContext()];
imgViewRight.frame = CGRectMake(imgView.frame.origin.x+imgView.frame.size.width/2, imgView.frame.origin.y,
imgView.frame.size.width/2, imgView.frame.size.height);
UIGraphicsEndImageContext();
[self.view addSubview:imgViewLeft];
[self.view addSubview:imgViewRight];
}