嗨,朋友们,我正在创建iPad应用程序,我在UIScrollView中使用UIImageView。因此,当我缩放图像并尝试绘制一些东西时,它不是在我触摸的那个点上绘制。我放大了多少,它在绘图中有所不同,并在左上角而不是中心创建图像.伙计们建议我。这是我的代码
if (isFreeHand==YES) {
mouseSwiped = YES;
UITouch *touch = [touches anyObject];
CGPoint currentPoint = [touch locationInView:self];
self.frame = CGRectIntegral(self.frame);
UIGraphicsBeginImageContextWithOptions(self.frame.size, self.opaque, 0.0);
[self.tempDrawImage.image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x-mWidht, lastPoint.y-mHeight);
CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x-mWidht, currentPoint.y-mHeight);
CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);
CGContextStrokePath(UIGraphicsGetCurrentContext());
self.tempDrawImage.image = UIGraphicsGetImageFromCurrentImageContext();
[self.tempDrawImage setAlpha:opacity];
UIGraphicsEndImageContext();
lastPoint = currentPoint;
}
缩放图像时,它看起来比实际大。它的原点可能不在 (0,0) 处。所以你必须重新计算触摸的实际位置。
澄清一下:
zoom scale ... zs
image offset ... (oX,oY)
touch coordinates ... (tX,tY)
translated touch ... (rtX,rtY)
如果缩放图像的原点仍在 (0,0) 中,则您将像这样翻译触摸:
rtX = tX/zs;
rtY = tY/zs;
如果图像原点将偏离 (0,0) 偏移量 (oX,oY),并且缩放比例将是 1.0,您将像这样翻译触摸:
rtX = tX+oX;
rtY = tY+oY;
将它们放在一起(偏移和缩放),翻译会去喜欢这个:
rtX = oX + tX/zs; //with oX zoomscale is allready taken into account
rtY = oY + tY/zs; //with oY zoomscale is allready taken into account
请注意,这些计算可能并不完全正确,因为我没有测试它们。但他们应该让你开始。
甚至可能有一个更优雅(内置)的解决方案来解决您的问题。
在第四行,将self
替换为 UIImageView 的名称:
CGPoint currentPoint = [touch locationInView: self.tempDrawImage];
位置InView实际上使触摸的坐标相对于某个UIView,这正是您所需要的。