Graphics Design in iPhone

Introduction 

In this article I will create a Single view application. Here we add a view on the window and draw a triangle, rectangle and ellipse using the "UIGraphicsGetCurrentContext"() method.

To understand it we use the following.

Step 1

Open XCode by double-clicking on it. 

Step 2

Create a New XCode Project by clicking on it.

Step 3

Now Select Single View Application and click on Next. 

Step 4

Now provide your Product Name.

Step 5

Select the location where you want to save your project and click on Create. 

Step 6

Now we write the code.

ViewController.m

#import "CircleView.h"

@implementation CircleView

- (id)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {

        // Initialization code

    }

    return self;

}


- (void)drawRect:(CGRect)rect {

// CGContextRef contextRef = UIGraphicsGetCurrentContext();

//

// CGContextSetRGBFillColor(contextRef, 0, 0, 255, 0.1);

// CGContextSetRGBStrokeColor(contextRef, 0, 0, 255, 0.5);

//

// // Draw a circle (filled)

// CGContextFillEllipseInRect(contextRef, CGRectMake(100, 100, 25, 25));

//

// // Draw a circle (border only)

// CGContextStrokeEllipseInRect(contextRef, CGRectMake(100, 100, 25, 25));

// Get the graphics context and clear it

CGContextRef ctx = UIGraphicsGetCurrentContext();

CGContextClearRect(ctx, rect);

// Draw a green solid circle

CGContextSetRGBFillColor(ctx, 0, 255, 0, 1);

CGContextFillEllipseInRect(ctx, CGRectMake(120, 100, 70, 70));

// Draw a yellow hollow rectangle

CGContextSetRGBStrokeColor(ctx, 255, 255, 0, 1);

CGContextStrokeRect(ctx, CGRectMake(195, 195, 60, 60));

// Draw a purple triangle with using lines

CGContextSetRGBStrokeColor(ctx, 255, 0, 255, 1);

CGPoint points[6] = { CGPointMake(100, 200), CGPointMake(150, 250),

CGPointMake(150, 250), CGPointMake(50, 250),

CGPointMake(50, 250), CGPointMake(100, 200) };

CGContextStrokeLineSegments(ctx, points, 6);

}

- (void)dealloc {

    [super dealloc];

}

@end

Step 7

Finally we click on the Run button to show the output.

Step 8

Output in iPhone:

Output-in-iPhone.png


Similar Articles