使用CGImageCreateWithImageInRect,UIImage和UIImagePickerController问题的好方法

Ada*_*dam 5 iphone uiimagepickercontroller uiimage

我正在尝试做一些理论上应该很简单的事情,但是我现在已经追了好几天了.我正在尝试从屏幕叠加中获取触摸事件,捕获图像,并在手指触摸的位置周围裁剪出一部分图像.

现在我所有的代码都工作得很好,覆盖,事件,裁剪等....但是我似乎无法获得触摸事件的坐标系来匹配UIImage的坐标系.我已经阅读了所有可以获得的文档,我似乎无法弄明白.

我的主要问题是,在使用CGImageCreateWithImageInRect时,我是否需要考虑UIImageOrientation,或者石英算出来了吗?我问的原因是我有一个非常简单的例程,裁剪图像很好,但裁剪的图像似乎永远不会被我的手指按下?

大部分例程是:

-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
 UIImage *image = =[info objectForKey:@"UIImagePickerControllerOriginalImage"];
 float scaleX = image.size.width / SCREEN_WIDTH;
 float scaleY = image.size.height / SCREEN_HEIGHT;
        //lastTouch is saved from touchesBegan method
 float x = (lastTouch.x * scaleX) - (CROP_WIDTH/2);
 float y = (lastTouch.y * scaleY) - (CROP_WIDTH/2);
 if(x < 0) x = 0.0;
 if(y < 0) y = 0.0;
        CGRect cropArea = CGRectMake(x, y, CROP_WIDTH, CROP_WIDTH);
 CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropArea);
 UIImage *swatch = [UIImage imageWithCGImage:imageRef];

        //at this point I'm just writing the images to the photo album to see if
        //my crop is lining up with my touch
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
        UIImageWriteToSavedPhotosAlbum(swatch, nil, nil, nil);
}
Run Code Online (Sandbox Code Playgroud)

所以,问题是我的裁剪区域(在我的相册中看到)从不匹配我按下的实际区域(它总是照片的其他随机部分),这让我觉得我的坐标系统已关闭.

任何指针都会非常感激,即使只是指向一些我还没有找到的文档.

干杯亚当

Sam*_*Sam 0

您必须始终记住,CoreGraphics 和 UIKit 之间的默认坐标系是不同的。UIKit 的原点位于窗口的左上角,而 CoreGraphics 则将此点设置在左下角。我认为这可能足以让您走上正轨,但只是重申一下:

您可以使用此代码来反转或翻转坐标系。

CGContextTranslateCTM(graphicsContext, 0.0, drawingRect.size.height);
CGContextScaleCTM(graphicsContext, 1.0, -1.0);
Run Code Online (Sandbox Code Playgroud)

另请参阅iOS 绘图和打印指南中的翻转默认坐标系