问题描述
我有一个自定义UIView,其中包含在视图的drawRect函数中绘制的交互式绘图。在iPad上,绘图尺寸为1024 x 768.对于iPhone,我使用CGContextScaleCTM缩小iPhone的绘图。为了在我的绘图上保持适当的宽高比,我将视图缩小到480 x 360并将视图的y值设置为-20(从视图的顶部和底部有效裁剪20个像素,这很好)。现在一切看起来都很正确,但是我需要将触摸坐标从iPhone转换为iPad坐标,以便我的视图的交互部分能够正常工作。如果我将uiview 320设为高并使用
I have a custom UIView that contains an interactive drawing that is drawn in the drawRect function of the view. On the iPad the drawing size is 1024 x 768. For the iPhone I shrink the drawing for the iPhone using CGContextScaleCTM. To keep the proper aspect ratio on my drawings I shrink the view to 480 x 360 and set the y value of the view to -20 (effectively cropping 20 pixels off the top and bottom of the View, which is fine). Everything looks correct now, but I need to convert the touch coordinates from iPhone to iPad coordinates for the interactive portions of my view to work. If I make the uiview 320 high and use
point.y *=768/320
用于转换y值的位置是正确的(但我的绘图是扭曲的)我已经做了一些测试硬编码点所以我知道这个应该工作,但我很难让数学与作物一起工作。以下是我到目前为止:
for converting the y value the locations are correct (but my drawing is distorted) I've done some tests hard coding point in so I know this should work but I'm having a hard time getting the math to work with the crop. Here is what I have so far:
CGPoint point = [[touches anyObject] locationInView:self.view];
[self endTouch:&point];
NSLog(@"true point: %@",NSStringFromCGPoint(point));
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
point.x *= 1024/480;
point.y *= 768/360;
NSLog(@"corrected point: %@",NSStringFromCGPoint(point));
}
有人可以帮我做这个转换吗?谢谢!
Can anybody help me with doing this conversion? Thanks!
推荐答案
1024/480
和 768/360
执行整数除法。两个操作的结果是 2
,但你真的想要 2.133333
。用以下内容替换代码中的相关行:
1024/480
and 768/360
perform integer division. The result of both operations is 2
, but you really want 2.133333
. Replace the relevant lines in your code with the following:
point.x *= 1024.0/480.0;
point.y *= 768.0/360.0;
这将返回您正在寻找的值并缩放您的点 x
和 y
相应的值。
This will return the value you're looking for and scale your point's x
and y
values accordingly.
您可能会更好地服务(就可读性而言) )用 #define
宏替换这些文字。在代码的顶部,输入以下内容:
You might be better served (in terms of readability) by replacing these literals with a #define
macro. At the top of your code, put the following:
#define SCALING_FACTOR_X (1024.0/480.0)
#define SCALING_FACTOR_Y (768.0/360.0)
然后修改你的代码使用:
and then modify your code to use that:
point.x *= SCALING_FACTOR_X;
point.y *= SCALING_FACTOR_Y;
这样,你会更清楚地知道你在做什么。
That way, it will be more clear as to what you're actually doing.
这篇关于将坐标从iPhone屏幕尺寸转换为iPad屏幕尺寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!