以下代码获取当前屏幕的UIImage:
UIGraphicsBeginImageContext(self.view.frame.size);
CGContextRef ctx = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:ctx];
UIImage *backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
如果我有一个CGRect rect并且我想只获取该rect中当前屏幕的UIImage,我该怎么办?
答案 0 :(得分:14)
获取矩形(裁剪)图像:
UIImage *croppedImg = nil;
CGRect cropRect = CGRectMake(AS You Need);
croppedImg = [self croppIngimageByImageName:self.imageView.image toRect:cropRect];
使用以下方法返回UIImage
(,如您所希望的图片尺寸)
- (UIImage *)croppIngimageByImageName:(UIImage *)imageToCrop toRect:(CGRect)rect
{
//CGRect CropRect = CGRectMake(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height+15);
CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return cropped;
}
答案 1 :(得分:0)
传递您想要裁剪的图像,并根据您的要求更改image.size.width和image.size.height
-(UIImage *)cropSquareImage:(UIImage *)image
{
CGRect cropRect;
if (image.size.width < image.size.height)
{
float x = 0;
float y = (image.size.height/2) - (image.size.width/2);
cropRect = CGRectMake(x, y, image.size.width, image.size.width);
}
else
{
float x = (image.size.width/2) - (image.size.height/2);
float y = 0;
cropRect = CGRectMake(x, y, image.size.height, image.size.height);
}
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
return [UIImage imageWithCGImage:imageRef];
}