Cropping CIImage with CICrop isn't working properly

拜拜、爱过 提交于 2019-11-29 22:36:20

Are you sure the output image is the size you are expecting? How are you drawing the output image?

The CICrop filter does not reduce the size of the original image, it just blanks out the content you don't want.

To get the result you want you probably need to just do this:

[image drawAtPoint:NSZeroPoint fromRect:NSMakeRect(150, 150, 300, 300) operation:NSCompositeSourceOver fraction:1.0];

If you want an actual CIImage as output rather than just drawing it, just do this:

CIImage* croppedImage = [image imageByCroppingToRect:CGRectMake(150, 150, 300, 300)];

//you also need to translate the origin   
CIFilter* transform = [CIFilter filterWithName:@"CIAffineTransform"];
NSAffineTransform* affineTransform = [NSAffineTransform transform];
[affineTransform translateXBy:-150.0 yBy:-150.0];
[transform setValue:affineTransform forKey:@"inputTransform"];
[transform setValue:croppedImage forKey:@"inputImage"];
CIImage* transformedImage = [transform valueForKey:@"outputImage"];
Chris Vander Mey

It's important to note that the coordinate system of a view is top-left-corner, whereas CIImage is bottom left. This will make you crazy if you don't catch it when you're doing these transforms! This other post describes a one-directional conversion: Changing CGrect value to user coordinate system.

This is how CICrop works -- it crop the rect you specified, and the un-cropped area becomes transparent. If you print extent you will see that it is still the same original rect.

As suggested, you can do a translation. This is now just 1 line, in Swift 5:

let newImage = myCIImage.transformed(by: CGAffineTransform(translationX: -150, y: -150)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!