到目前为止,这就是我取得成功的地方。我正在使用从相机捕获的UIImage,可以在风景中裁剪中心正方形。由于某些原因,这并不能像预期的那样转换为纵向模式。我将发布我的代码和日志,仅供参考。
代码:
CGRect squareRect = CGRectMake(offsetX, offsetY, newWidth, newHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], squareRect);
image = [UIImage imageWithCGImage:imageRef scale:1 orientation:image.imageOrientation];纵向结果(不是正方形):
original image size: {1536, 2048}, with orientation: 3
squareRect: {{0, 256}, {1536, 1536}}
new image size: {1280, 1536}, with orientation: 3 <--- not expected横向结果(正方形):
original image size: {2048, 1536}, with orientation: 1
squareRect: {{256, 0}, {1536, 1536}}
new image size: {1536, 1536}, with orientation: 1这是CGImageCreateWithImageInRect()中的一个错误,还是我在这里遗漏了什么?
发布于 2015-04-15 15:02:21
从@Elmundo的答案改进
+(UIImage *)getCenterMaxSquareImageByCroppingImage:(UIImage *)image withOrientation:(UIImageOrientation)imageOrientation
{
CGSize centerSquareSize;
double oriImgWid = CGImageGetWidth(image.CGImage);
double oriImgHgt = CGImageGetHeight(image.CGImage);
NSLog(@"oriImgWid==[%.1f], oriImgHgt==[%.1f]", oriImgWid, oriImgHgt);
if(oriImgHgt <= oriImgWid) {
centerSquareSize.width = oriImgHgt;
centerSquareSize.height = oriImgHgt;
}else {
centerSquareSize.width = oriImgWid;
centerSquareSize.height = oriImgWid;
}
NSLog(@"squareWid==[%.1f], squareHgt==[%.1f]", centerSquareSize.width, centerSquareSize.height);
double x = (oriImgWid - centerSquareSize.width) / 2.0;
double y = (oriImgHgt - centerSquareSize.height) / 2.0;
NSLog(@"x==[%.1f], x==[%.1f]", x, y);
CGRect cropRect = CGRectMake(x, y, centerSquareSize.height, centerSquareSize.width);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
UIImage *cropped = [UIImage imageWithCGImage:imageRef scale:0.0 orientation:imageOrientation];
CGImageRelease(imageRef);
return cropped;
}https://stackoverflow.com/questions/14203951
复制相似问题