Wednesday, February 23, 2011

iPhone : Resizing image and maintain aspect ratio

Issue : While scaling an image to fit to an image view [CGRect ....],Image was distorting.
Reason: Image stretches/compress itself to fit to specified area and usually get distorted.
So in order to maintain the actual aspect ratio of the image We can use this:

In Header file, Declare a method:

-(UIImage *)resizeImage:(UIImage *)image withWidth:(int) width withHeight:(int) height;

In (implementation).m file :
We need to define radians macro,this will be used in function definition declared above.

static inline double radians (double degrees) {return degrees * M_PI/180;}

Function definition:

-(UIImage *)resizeImage:(UIImage *)image withWidth:(int) width withHeight:(int) height {

CGImageRef imageRef = [image CGImage];
CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo(imageRef);
CGColorSpaceRef colorSpaceInfo = CGColorSpaceCreateDeviceRGB();

if (alphaInfo == kCGImageAlphaNone)
alphaInfo = kCGImageAlphaNoneSkipLast;

CGContextRef bitmap;

if (image.imageOrientation == UIImageOrientationUp | image.imageOrientation == UIImageOrientationDown) {
bitmap = CGBitmapContextCreate(NULL, width, height, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, alphaInfo);

} else {
bitmap = CGBitmapContextCreate(NULL, height, width, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, alphaInfo);

}

if (image.imageOrientation == UIImageOrientationLeft) {
NSLog(@"image orientation left");
CGContextRotateCTM (bitmap, radians(90));
CGContextTranslateCTM (bitmap, 0, -height);

} else if (image.imageOrientation == UIImageOrientationRight) {
NSLog(@"image orientation right");
CGContextRotateCTM (bitmap, radians(-90));
CGContextTranslateCTM (bitmap, -width, 0);

} else if (image.imageOrientation == UIImageOrientationUp) {
NSLog(@"image orientation up");

} else if (image.imageOrientation == UIImageOrientationDown) {
NSLog(@"image orientation down");
CGContextTranslateCTM (bitmap, width,height);
CGContextRotateCTM (bitmap, radians(-180.));

}

CGContextDrawImage(bitmap, CGRectMake(0, 0, width, height), imageRef);
CGImageRef ref = CGBitmapContextCreateImage(bitmap);
UIImage *result = [UIImage imageWithCGImage:ref];

CGContextRelease(bitmap);
CGImageRelease(ref);

return result;
}

Tuesday, February 15, 2011

iPhone : Add vibration to your iPhone App code

Add the folowing framework :
AudioToolbox.framework

Import:
#import <AudioToolbox/AudioServices.h>

Now use this line of code to make iPhone vibrate:
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Monday, February 7, 2011

textFieldShouldBeginEditing called twice in iOS4

UITextField textFieldShouldBeginEditing called twice in iOS4
When you tap UITextField, you get two textFieldShouldBeginEditing calls. This looks like a bug in initial iOS4 release.