Skip to main content
Category

Blog

UIImage ScaleToFit

By Blog

Sometimes the image provided by the UIImagePicker is not the right size, and putting it to the UIImageView is not enough as we do need to know the size it was being fit to.

 


Let’s cut the chase, here is the code:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public static class UIImageUtils
{
///
///
///
///
/// A
///
public static UIImage ScaleToFit(UIImage sourceImage, System.Drawing.SizeF targetSize)
{
UIImage newImage;
 
SizeF imageSize = sourceImage.Size;
float width = imageSize.Width;
float height = imageSize.Height;
 
float targetWidth = targetSize.Width;
float targetHeight = targetSize.Height;
 
float scaleFactor = 0f;
float scaledWidth = targetWidth;
float scaledHeight = targetHeight;
 
PointF thumbnailPoint = new PointF(0, 0);
 
if (imageSize != targetSize)
{
float widthFactor = targetWidth / width;
float heightFactor = targetHeight / height;
 
if (widthFactor < heightFactor)
scaleFactor = widthFactor;
else
scaleFactor = heightFactor;
 
scaledWidth = width * scaleFactor;
scaledHeight = height * scaleFactor;
 
// center the image
 
if (widthFactor < heightFactor)
{
thumbnailPoint.Y = (targetHeight - scaledHeight) * 0.5f;
}
else if (widthFactor > heightFactor)
{
thumbnailPoint.X = (targetWidth - scaledWidth) * 0.5f;
}
}
 
RectangleF thumbnailRect = new RectangleF(new PointF(0, 0), new SizeF(scaledWidth, scaledHeight));
 
UIGraphics.BeginImageContext(thumbnailRect.Size);
 
sourceImage.Draw(thumbnailRect);
 
newImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
 
return newImage;
}
}

Hope this helps.

Happy coding!

Tap gesture without UITapGestureRecognizer

By Blog

Ever needed to handle the tap event but needed to distinguish between tap and double tap? I guess everybody sometimes get to such issue and surprisingly prior iOS 4 there is no simple way how to do it.

With iOS4 you just call UITapGestureRecognizer and you are ready to go, so how to do it with version prior iOS4? Here you go:

 

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	NSUInteger numTaps = [[touches anyObject] tapCount];
 
	if (numTaps < 2) 
	{
		[self performSelector:@selector(doSomeSingleTapAction) withObject:nil afterDelay: 0.25];
 
		[self.nextResponder touchesEnded:touches withEvent:event];
	} 
     	else 
     	{
		if(numTaps == 2) 
          	{
			[NSObject cancelPreviousPerformRequestsWithTarget:self];
 
			[self performSelector:@selector(doSomeDblTapAction) withObject:nil afterDelay: 0.25];
		}		
 
	}
}

 

Happy coding!