How to perform animated rotation of a view using core graphics?

This post deals with rotating a view with animation with the help of core graphics. Quartz framework provides us with class “CGAffineTransform.h” which contains the function “CGAffineTransform CGAffineTransformRotate ( CGAffineTransform t, CGFloat angle );” that takes the current affine transform matrix and angle in radians as parameters, and returns the resultant affine transform. We will also animate the rotation instead of simply rotating the view by some angle.

Now lets see how it is done.

Suppose we have a view controller class called RotationViewController.

Write the following code in RotationViewController.h” file

 

#import <UIKit/UIKit.h>

@interface RotationViewController : UIViewController {
	UIImageView *needleview;
	}

@end

Here needleview is the view we are going to rotate.

Now come to RotationViewController.m file and write the following code

 

- (void)viewDidLoad {
	needleview=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"finalneedle.png"]];
	needleview.frame=CGRectMake(100, 100, 36, 221);
	[self.view addSubview:needleview];
    [super viewDidLoad];
}

-(void)viewDidAppear:(BOOL)animated
{
	[UIView animateWithDuration:2.0

	 delay: 0.0

	options: UIViewAnimationOptionCurveEaseIn

	animations:^{

	needleview.transform=CGAffineTransformRotate(needleview.transform, (((60*22)/7)/180));

	 }
	 completion:nil];

}

In the above code “finalneedle.png” is the image file, in the resources folder, to be used in ImageView. We have implemented “viewDidAppear” to perform rotation with animation after the view appears on screen. The animation block inside the method contains various parameter which has to be set before animating the rotation. The angle of rotation is 60 degree which is converted to radians.

How to make a custom view in iPhone application?

This post deals with making custom views in iPhone application. You can design your views according to your ideas rather than using plain UIView. You can draw variety of patterns in your custom views using Quartz framework and then use these views in your application.

In this snippet we will add a simple coloured rectangle in a view.

1) Add a new file in your project and select it as a subclass of UIView as shown in figure.

 

2) Lets name it as “new”, so now you must have got two files “new.h” and “new.m” . new.h inherits UIView.

3) Lets say we have a view controller. Open its xib file, select view in file owner window and change its class from UIView to new in library inspector window as shown in figure.

 

4) Now come to new.m file, uncomment and ovewrite its “drawRect:” method with code shown below

- (void)drawRect:(CGRect)rect {
    // Drawing code.
	CGContextRef context = UIGraphicsGetCurrentContext();
	CGContextSetRGBStrokeColor(context, 1.0f, 0.3f, 0.5f, 1.0f);
	CGContextStrokeRectWithWidth(context,CGRectMake(20, 20, 280, 420), 10);
}

5) Save, build and run the project.

6) Output is as shown below. Now you can use this view in any view controller in your application.

How to take screenshot of the iPhone screen programmatically?

This post deals with taking screenshot of the iPhone screen with the help of coding.

Remember, when we say screen shot of the iPhone screen, we mean screenshot of any view which is visible on the iPhone screen. Also, a view is captured with all its subviews that are visible on screen at the time of capturing.

Add the following code at the place where you want to take screenshot of the view.

UIGraphicsBeginImageContext(view.frame.size);
	CGContextRef context = UIGraphicsGetCurrentContext();
	[view.layer renderInContext:context];
	UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();

A Context, more accurately known as Graphics Context, is the drawing destination for your objects. A context can be a Bitmap image, a UIView layer, a PDF file or a Printer.

In the above code, view is the UIView object which has to be captured.

UIGraphicsBeginImageContext(view.frame.size) creates a  bitmap image context and set it as the current context. It takes size as parameter. The image context made is of the same size as the size passed in as parameter to this function. Since, here we want the image context to be of same size as of view to be captured so we pass the size of view as parameter.

UIGraphicsGetCurrentContext() returns the current context for drawing. Since we already set the bitmap context as the current context so it will return the same bitmap context created above. Had the bitmap context not been set , all the drawings would have taken place on UIView layer context(which is the default current context).

[view.layer renderInContext:context] draws all the objects, on or above the view’s layer, to the context passed in as parameter.

UIGraphicsGetImageFromCurrentImageContext() returns an image based on the contents of the current bitmap-based graphics context.

How to animate switching of views?

This snippet deals with animating switching of views.

 

Normally when users have to switch views they simply add the following code

[self.view addSubview:someview];

and to remove this view from superview they use

[self.view removeFromSuperview];

The above code do not perform any animations while switching views. They simply switch.

Adding few lines of code can make switching of views more interesting.

While you add or remove views just do it inside following code to add life to the switching of views.

 

[UIView beginAnimations:@"flipping view" context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.view cache:YES];
[self.view addSubview:someViewController.view];
[UIView commitAnimations];

Now lets see what these lines of code do.

1) begin Animations: start our animation block. You can give any name in place of @”flipping view”.

2) setAnimationDuration: sets the duration for which the animation will last.

3) setAnimationCurve: sets the curve of animating property changes with in an animation. You can use following constants in this place

➤    UIViewAnimationCurveEaseInOut —cause the animation to begin slowly, accelerate through the middle of its duration, and then slow again before completing.

➤    UIViewAnimationCurveEaseIn — causes the animation to begin slowly and then speed up as it progresses

➤    UIViewAnimationCurveEaseOut — causes the animation to begin quickly and then slow as it completes

➤    UIViewAnimationCurveLinear — causes an animation to occur evenly over its duration

4) setAnimationTransition: applies a transition type to the animation. Following constants can be used.

➤ UIViewAnimationTransitionNone — no transition

➤ UIViewAnimationTransitionFlipFromLeft — flips a view around vertical axis from left to right

➤ UIViewAnimationTransitionFlipFromRight — flips a view around a vertical axis from right to left

➤ UIViewAnimationTransitionCurlUp — curls a view up from the bottom

➤UIViewAnimationTransitionCurlDown — curls a view down from the top

5) addSubView: is the usual method by which you add a subview to a view. Here someViewController is a class object whose view we want to add.

6) In the end we commit our animation block.

How to find date and time programmatically in different formats?

This post deals with finding out date and time programmatically in different formats.

Open .xib file

Drag 6 labels and arrange them as shown in figure

Name of the labels are

1)Date

2)label2

3)Time

4)label2

5]Date and Time with time zone

6)label3

Now come to .h file

Write the following highlighted lines of code

Now move to .m file

synthesize these labels

@synthesize label1,label2,label3;

Now in viewDidLoad function write the following code

NSDate *now = [[NSDate alloc] init];

	NSDateFormatter *df = [[NSDateFormatter alloc] init];

[df setDateFormat:@"yyyy-MM-dd"];
	NSString *date=[df stringFromDate:now];
	label1.text=date;
	 df = [[NSDateFormatter alloc] init];

	[df setDateFormat:@"hh:mm:ss a"];
	date=[df stringFromDate:now];
	label2.text=date;
	[df setDateFormat:@"yyyy-MM-dd hh:mm:ss a zzz"];
	date=[df stringFromDate:now];
	label3.text=date;

In the above code we can see that three different formats for date and time have been set. You can try your own format also for example “yyyy” will give only year.

Now  open Interface Builder and make connections as shown in figure

 

Save and build the application. You will get output like shown below

 

How to display a custom view instead of standard keyboard when the textfield becomes first responder?

This snippet deals with how to display custom view instead of keyboard when the textfield becomes first responder…

 

Write the highlighted code, as shown below, in .h file

Now come to .m file and write the code give below

@synthesize field;

Inside viewDidLoad method write the following code

UIImage *image=[UIImage imageNamed:@"apple-logo.jpg"];
	UIImageView *view=[[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100, 200.0f)];
	[view setImage:image];

	field.inputView=view;

Here apple-logo.jpg is the image in the resource folder

 

Now come to .xib

Add a textfield and a label as shown below. Also make the connection

Now when you interact with textfield you will get your own view instead of keyboard

How to use UIPickerView?

This post deals with using UIPickerView in an application

 

Lets say the ViewController class in which UIPickerView is to be populated is myViewController

Open myViewController.xib

Drag UIPickerView from Library and add it to the view as shown below

iPhone Application Tutorials

Now come to myViewController.h file

Add the following lines of code highlighted

Now move to myViewController.m

Add the following code

@synthesize picker;

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
	return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
	return 3;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
	return @"john";
}

The above delegate methods take care of following conditions

In the above code we have assumed that number of components is 1 and there are 3 rows in that component

We want to populate the rows with “john”

Save all this

Now it’s time to make connections, so come again to myViewController.xib

Make connections as shown below

iphone Application Tutorials

Save and execute and the output is shown below

iPhone Application Tutorials