7/01/2009

[iPhone] Quartz 2D

Quartz ComposerImage via Wikipedia

The last week I've been fighting to get some stuff working in Quartz. Actually I've been trying to get Quartz itself to work.
I've now managed and thought I could share:

Open your viewController.xib and add a view inside your view. Size it and move it the way you want it. This is the view that you will use like a tv screen, showing all your Quartz drawing.
(This is the way I am doing it for a specific app. I'm sure you'll find your way that fits your app the most.)

Select the view and press ⌘4 and change the class to, lets say, "QuartzView".
Select File>Write Class File and check the box to create the .h file too.

Once created, the files will be in your project.
in the QuartzView.h:
@interface QuartzView : UIView {
UIColor *color;
}
@end
Switch over to the .m file.
The drawRect method is the one where we'll do all the drawing. The drawing code has to be in this method as far as I know.

Lets start filling in some code in the drawRect method then and try to draw a line.
First, we set the color for our line and retrieve the context. The context is like your canvas where you'll be drawing. All the drawing is done in a context. As we'll only have one context, I'll call it (who would have guessed) "context" :

color = [UIColor redColor];
CGContextRef context = UIGraphicsGetCurrentContext();

Then, we set some properties of the line we're going to draw. They are pretty self explanatory. You always define the context (which we cleverly called "context") and the specific attribute of the property.

CGContextSetLineWidth(context, 2.0); // We set a 2px thick line.
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGContextSetFillColorWithColor(context, color.CGColor);
//This settings want a CGColor and not a UIColor. Good for us, UIColor has a property that returns the color as a CGColor.
Now that we've set the properties of the line we're about to draw, lets prepare the actual movement required to draw a line.

We'll create 2 CGPoints which basically just group an X & Y coordinate of the screen in one variable.

CGPoint startingPoint = CGPointMake(20.0, 20.0);
CGPoint finishingPoint = CGPointMake(80.0, 80.0);

Now, we move our virtual drawing hand (with the pencil we've defined earlier) to the starting point and then make it move to the finishing point. We then just have to say to actually draw that line and to update our view. 4 lines of code.

CGContextMoveToPoint(context, startingPoint.x, startingPoint.y);
CGContextAddLineToPoint(context, finishingPoint.x, finishingPoint.y);
CGContextStrokePath(context);
[self setNeedsDisplay];
Right, so that's the basics. I'll probably go into more details once I've figured it out better myself soon.
Reblog this post [with Zemanta]

No comments:

Post a Comment