Reputation: 309
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
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!
Upvotes: 2
Views: 2071
Reputation: 2610
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;
This will return the value you're looking for and scale your point's x
and y
values accordingly.
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.
Upvotes: 3