在macOS编程中,我们知道
现在我正在使用Quartz API-CGImageCreateWithImageInRect裁剪图像,该图像将矩形作为参数。 rect的Y起源来自可可的mousedown事件。
因此,我在倒置的地方种植农作物...
我尝试使用此代码在我的cropRect中翻转Y坐标
//Get the point in MouseDragged event
NSPoint currentPoint = [self.view convertPoint:[theEvent locationInWindow] fromView:nil];
CGRect nsRect = CGRectMake(currentPoint.x , currentPoint.y,
circleSizeW, circleSizeH);
//Now Flip the Y please!
CGFloat flippedY = self.imageView.frame.size.height - NSMaxY(nsRectFlippedY);
CGRect cropRect = CGRectMake(currentPoint.x, flippedY, circleSizeW, circleSizeH);
但是对于顶部区域,我错了FlippedY坐标。 如果我单击视图顶部边缘附近,我会翻转Y = 510至515 在顶部边缘应该在0到10之间:-|
有人可以指出我正确且可靠的翻转方式吗 在这种情况下的Y坐标?谢谢!
这是GitHub中的示例项目,突出了该问题 https://github.com/kamleshgk/SampleMacOSApp
答案 0 :(得分:1)
正如Charles所述,您使用的Core Graphics API需要相对于图像(而不是屏幕)的坐标。重要的是将事件位置从窗口坐标转换为最接近图像位置的视图,然后相对于同一视图的边界(不是框架)翻转它。所以:
NSView *relevantView = /* only you know which view */;
NSPoint currentPoint = [relevantView convertPoint:[theEvent locationInWindow] fromView:nil];
// currentPoint is in Cocoa's y-up coordinate system, relative to relevantView, which hopefully corresponds to your image's location
currentPoint.y = NSMaxY(relevantView.bounds) - currentPoint.y;
// currentPoint is now flipped to be in Quartz's y-down coordinate system, still relative to relevantView/your image
答案 1 :(得分:0)
您传递给CGImageCreateWithImageInRect
的矩形应该在相对于输入图像尺寸的坐标中,而不是屏幕坐标中。假设输入图像的大小与将点转换为视图的大小相匹配,则应该能够通过从图像的高度而不是屏幕的高度减去矩形的角来实现此目的。