27th December 2008

Gravity Tutorial for iPhone Part 2

posted in Objective C, iPhone |

See this note.

In part 1, we created a Ball class which contained position, velocity, radius, and a color. And we set up a timer to update the ball's position based on its velocity and bounce off the walls.

Now let's render that ball to the screen.

Rendering is done in a view class, which is of type UIView or a sublcass of UIView. when you create a View-Based application, XCode automatically sets up a generic view of type UIView. Often this is fine, but since we need to do some drawing with code, we need to have a custom view class.

So create a new file with the UIView subclass template. Name it BallView. This will create BallView.h and BallView.m files.

We're going to need a method to tell the view to refresh, and something to tell it where to draw the ball. Here's the header:

C:
  1. #import <UIKit/UIKit.h>
  2.  
  3.  
  4. @interface BallView : UIView {
  5.     CGRect ballRect;
  6. }
  7.  
  8. - (void)refresh:(CGRect)rect;
  9.  
  10. @end

Here we have a CGRect which is a data class that holds a rectangle definition. That's a private variable. And we have a refresh method that takes a CGRect as a parameter. Funky syntax there if you are coming from an ActionScript world, but you'll learn to love it. :)

In the BallView.m file, we'll implement the refresh method:

C:
  1. - (void)refresh:(CGRect)rect {
  2.     ballRect = rect;
  3.     [self setNeedsDisplay];
  4. }

This assigns the rect parameter to the ballRect class variable, and tells the view that it needs to re-display itself. When this happens, the drawRect method of the view will run. That is already defined for you, with a space to add your code.

Think of a view like an ActionScript DisplayObject. In ActionScript, you need to get the graphics object of the display object to do any drawing. In UIView you need to get a Core Graphics context. That's done with the UIGraphicsGetCurrentContext method, which returns an instance of CGContextRef. Then you set the line width, line color, fill if necessary, add some points, lines, shapes, or whatever to a path, then draw or stroke the path. I won't go into it in detail. I'm sure when you see the code, you'll get the idea pretty readily.

C:
  1. - (void)drawRect:(CGRect)rect {
  2.     // Drawing code
  3.     CGContextRef context = UIGraphicsGetCurrentContext();
  4.     CGContextSetStrokeColorWithColor(context, [UIColor greenColor].CGColor);
  5.     CGContextSetLineWidth(context, 1.0);
  6.     CGContextAddEllipseInRect(context, ballRect);
  7.     CGContextStrokePath(context);
  8. }

Dig through the references for anything that begins with CGContext to get a feel for the different drawing API commands. I skimped here and just hard coded green as the drawing color. This really should be passed in with the refresh method. Or maybe even pass in the whole ball instance, but this works fine for now. As I said, we get the context, set the stroke color and line width, add an ellipse using the ballRect that we just saved and stroke the generated path.

OK. Our BallView class is complete. Now we need to tell XCode to use this class instead of the default one provided in the template. To do this, we need to go into Interface Builder. OK, we don't NEED to. There are ways to do it with code too. But in this tutorial, that's how we are going to do it.

Think of Interface Builder as Flex Builder's design view. IB generates .xib files which are actually xml files, though I'm not sure anyone actually edits xib files by hand like they do with mxml files.

In the resources folder of your project, you should see a GravityTutorialViewController.xib file. Double click on that and IB will launch.

In the Document window you should see three icons - File's owner, First Responder, and View. I'll leave it to you to learn about the first two. Here were are concerned with the View. Click on it and open up the Identity Inspector window. At the top of that you should see a Class dropdown with UIView selected. This is telling you that the default view used for this project is a generic instance of the UIView class. We want it to use BallView instead. Simple enough. Just click on the dropdown and change the class to BallView. The icon label should now say "Ball View". Good. Now you might want to open the Attributes Inspector window and change the background color to black or something other than gray.

Save the .xib file, and exit IB if you want, because we are done with it.

Back to XCode. You should be able to run the app again with the same results as before. You still won't see anything, but it should compile and run with no errors or warnings. And if you have the console open, you should still get the log statements showing position.

Now, back in our GravityTutorialViewController.m file, in the onTimer method, we need to tell the view to refresh, passing in the rectangle of the ball's location and size.

First we'll create the rectangle, which is based on the ball's position and radius. Then we need to call refresh on the view. The view controller has a view property that refers to the view, but the problem is that it is typed as a pointer to UIView. So we'll need to cast it to a pointer to BallView or we'll get a compile error when we try to call the refresh method.

C:
  1. - (void)onTimer {
  2.     [ball update];
  3.     CGRect rect = CGRectMake(ball.position.x - ball.radius, ball.position.y - ball.radius, ball.radius * 2.0, ball.radius * 2.0);
  4.     [(BallView *)self.view refresh:rect];
  5. }

Also, this is the first time we've used the BallView class in this class, so we'll need to import it at the top of the class:

C:
  1. #import "GravityTutorialViewController.h"
  2. #import "BallView.h"
  3.  
  4. @implementation GravityTutorialViewController
  5. ...

You can remove the NSLog statement now, as you should actually have a real moving ball now. Build and go, and behold your bouncing ball!

In Part 3, we'll do some enhancements and even add gravity!

Post to Twitter

This entry was posted on Saturday, December 27th, 2008 at 2:35 pm and is filed under Objective C, iPhone. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

There are currently 15 responses to “Gravity Tutorial for iPhone Part 2”

  1. 1 On December 29th, 2008, 4 part iPhone Development Tutorial on Gravity from Keith Peters at The iPhone Developer Chronicles said:

    [...] Gravity Tutorial for iPhone – Part 2 [...]

  2. 2 On December 30th, 2008, Bob said:

    Hey Keith! This tutorial is great for an old as developer! :) Although i get myself some errors while compiling that i’m not sure how to debug:

    Undefined symbols:
    “_CGContextAddEllipseInRect”, referenced from:
    -[BallView drawRect:] in BallView.o
    “_CGContextSetLineWidth”, referenced from:
    -[BallView drawRect:] in BallView.o
    “_CGContextStrokePath”, referenced from:
    -[BallView drawRect:] in BallView.o
    “_CGContextSetStrokeColorWithColor”, referenced from:
    -[BallView drawRect:] in BallView.o
    ld: symbol(s) not found
    collect2: ld returned 1 exit status

    Does it miss some imports or what symbols is it talking about?

    Thanks for giving us a kick in the right direction! ;)

    /bob

  3. 3 On December 30th, 2008, Bob said:

    Nvm, i missed your notice in the beginning, after adding CoreGraphics.framework it compiles nicely!

  4. 4 On December 30th, 2008, Scott Janousek said:

    After crashing XCode a few times … Bouncing Ball success!

  5. 5 On December 31st, 2008, IPhone SDK - tutoriaux par Keith Peters | tweenpix said:

    [...] la liste complète des tutoriaux: – Part 1 – Part 2 – Part 3 – Part 4 – Part [...]

  6. 6 On January 2nd, 2009, WS-Blog » WSPluginSwitcher: Cocoa based tool for switching Flash plug-in on OS X said:

    [...] Peters: Gravity Tutorials for iPhone, Part 1, Part 2, Part 3, Part 4, Part [...]

  7. 7 On February 22nd, 2009, イナヅマtvログ » iPhone SDK + Objective-C, 参考サイト メモ said:

    [...] Gravity Tutorial for iPhone – Part 2 [...]

  8. 8 On June 18th, 2009, meng said:

    The last step when I’m supposed to change UIView to BallView, BallView is not in the dropdown and if I type it in, it just disappears after I save. I know I’m missing something, help?

  9. 9 On June 18th, 2009, meng said:

    Nevermind, I created the BallView files as NSObject subclass instead of View

  10. 10 On July 3rd, 2009, Rameen said:

    The edges of the circle blur when in motion. How would you go about making it smooth and seamless?

  11. 11 On July 6th, 2009, Jack Cardinal said:

    Awesome tutorial Keith. Thanks!

  12. 12 On July 15th, 2009, Benedikt Reiter said:

    in this line the following error occours:
    [(BallView *)self.view refresh:rect];

    2009-07-15 14:36:46.751 BallDemo[2697:20b] x: 104.000000, y: 103.000000
    2009-07-15 14:36:46.753 BallDemo[2697:20b] *** -[MainView refresh:]: unrecognized selector sent to instance 0xd29ac0
    2009-07-15 14:36:46.754 BallDemo[2697:20b] *** Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[MainView refresh:]: unrecognized selector sent to instance 0xd29ac0′

    what 2 do now?

  13. 13 On July 18th, 2009, johnny_g said:

    Yah, I am also getting the same errors as Benedikt…. whats up with that?

  14. 14 On August 7th, 2009, Learning Iphone » Gravity Tutorial for iphone said:

    [...] the link, let’s see how much I can do tonight before I gotta get to bed. – Part 1 – Part 2 – Part 3 – Part 4 – Part [...]

  15. 15 On January 14th, 2010, Carey said:

    I get a warning that says ‘NSTimer’ may not respond to ‘+scheduledTimerWithTimeInterval: etc. in the viewController.m. When I launch the simulator, it just shuts opens and shuts down again.

Leave a Reply

Who is reading BIT-101?

Copyright ©2009 by Keith Peters. All rights reserved. This means that you may not reprint or repost the contents of this site without express written permission of the author.


  • Calendar

  • February 2010
    M T W T F S S
    « Jan    
    1234567
    891011121314
    15161718192021
    22232425262728
hoodia order buy Levitra Plus betablockers weight loss information buy pills without a prescription arthritis menopause ambien doses cat's eye health information on cholesterol cialis online order valtrex cheapest phentermine onlin e increase breast size lower blood sugar immediately terramycin which is better cialis or viagra buy cheap cialis reduce cholesterol naturally new blood pressure treatment products for back pain cheapest cialis index will levitra help piroxicam 20 mg order viagra online in germany buy tadalafil online buy levitra onlines how to naturally lower cholesterol buy generic viagra where to buy soma anti allergic drug levothyroxine dogs new hair loss treatmen buy levitra pain meds buy cheap malaria therapy weight loss after baby asthma medications chronic snoring viagra gel prostate cancer cures order viagra cialis alprazolam men health natural cure arthritis immune system support diet medicine cialis approval lipitor effects where can i buy arthritis drugs overactive bladder in men self help weight loss natural cholesterol control ativan medication cialis approval best cure for snoring breast enhancing pills order prozac celebrex pharmacy buy levitra onlines premature ejaculation cure confidence hypnotherapy free stop smoking bust enhance diet weight loss supplements skin fungal infection valium with no prescription viagra with out prescription breast enhancement products alpha blocker medications azithromycin 250mg skin disease chronic heart failure medicines dog care products buying cialis online gerd in children antibiotics to buy my drug store muscle building diet drugs affecting levitra anti anxiety medications really large breast enhancement help for constipation ulcers stomach drugs for high blood pressure selling pet products buy pain medicine viagra online overnight fucidin ointment generic zyrtec prices soft tab cialis smoking treatment dog products online weight loss solution cialis on line blue pills weight loss diet pill nitroglycerin sublingual floxin prevention of heart attack imuran order gasex vermox treatment of depression Viagra On Line buy generic cialis professional tooth whitening kits to buy valium 2mg treatment for hypertension ultram cheapest online stores hair loss products cheap weight loss diovan prescription malaria preventative taurine treating prostate cancer immune system support natural constipation cure phentermine no prescription fast delivery purchase meds without prescription buy plendil diet drug taking viagra after cialis protonix cheapest generic cialis online viagra levitra cialis yohimbe benefits muscle mass gain diet and health products medical treatment for insomnia buy blood pressure meds buy celexa levaquin interactions blood pressure drug skin disorder where can i buy arthritis drugs natural breast enhancer acute pain control online diazepam natural acne remedy antifungal strategies triphala pravachol online how can i stop smoking breast enhancement natural nautral breast enhancement beta blocker medications wellbutrin dosages order viagra cialis lower high blood pressure mass muscle phentermine from canada how to loss weight osteoporosis bone health lipitor use dog medication drug allergies buy diazepam buyviagra cialis phentermine 37.5 mg zestril medication parkinsons treatment generic revatio free nexium cosmetic dentistry tooth whitening avalide generic buy cheap tadalafil uk simvastatin tablets buy cialis online in usa breast pain cat care ovulating clomid medical skin care lines viagra to canada viagra or cialis cheap cialis tramadole buy azulfidine drugs used for cancer ear pain oral ketoconazole raloxifene evista taurine sex with levitra stop smoking today heart failure natural cholesterol control protonix dose oxybutynin 5mg irritable bowel syndrome treatments new treatment for hepatitis c cheap prescription drugs viagra online prescription depression therapy buy sumycin menopause treatment hair loss treatments medication pletal what is a natural antibiotic viagra purchase synthroid tablets generic prilosec lipitor cat health info discount vitamin cholesterol and health bacterial diarrhea weight loss medicine new treatment for depression removing retention fluids diuretic medicines soma 250mg cat anxiety loss weight online pharmacy viagra buy phentermine without a prescription herbs for breast growth cymbalta dosage fast weight loss supplement arthritis menopause levitra online order cheapest place to buy phentermine cold flu medications for nausea buy ultram where pills for acne free weight loss programs help with anxiety improve skin valium 2mg urinary tract health cat urinary tract disease crestor dosage drug zofran calan zyrtec buy nirdosh dosage digoxin buy pain patch acomplia alendronate cialis best price cheap wellbutrin small dog products depression medicine sildenafil dosage dog health depression and anxiety lamictal withdrawal viagra, levitra and cialis online drug buy bone maker strontium cures for hair loss nitroglycerin tablets natural arthritis treatment arimidex buy buy energy patch how to treat a yeast infection viagra herb alternative viagra cialis levitra order sublingual cialis cialis comparison breast lift augmentation seroquel for depression carisoprodol mg new treatment for depression cialis soft tabs safe sleep aid severe leg muscle pain natural weight loss gabapentin medication what is ambien clozapine medication viagra online ordering cures for hair loss free weight loss help buy viagra levitra pet treats order plan b diabetes type 2 phentermine risk ultram er side effects treatment for hepatitis b constipation cures drugs used in treating depression leg pain buy cheap generic cialis anti anxiety meds hypnotherapy for weight loss motilium body building fitness dog skin relieve upper back pain cures for high blood pressure cardura celecoxib Viagra Online Cheap cheap bactrim ambien online lamisil cost infertility meds progesterone clomid osteoporosis hormon urinary tract infection symptoms hypnotherapy for health how to buy viagra online joint pain cure online allegra buy generic cialis uk generic abilify cures for lung cancer new treatments for lung diseases pain meds buy cheap treatment for dry skin disease of the skin nexium drug free stop smoking buy tooth whitening products viagra tablet naprosyn dosage women's fertility male sexual power carisoprodol purchase asthma attack treatment estradiol pills phentermine from canada pet health care hair loss products online astelin generic cheap estrace free weight loss program buy rimonabant relieve lower back pain lexapro prescription new breast cancer drug buying ambien best online viagra scams home scabies treatment hair loss in woman buy generic cialis uk eye drop gabapentin medication amitriptyline uses ultram no prescription natural pain cures buy cla products back pain lowest price generic viagra pain meds buy cheap mg buy phentermine acne skin care cialis rx weight loss and fitness nitrofurantoin buy phentermine without a prescription high blood pressure medicines stop hair loss viagra china use levitra female health coreg dosage carisoprodol price pain relief product breast enlargement depression pills buy how to treat flu home neck pain relief order imitrex online vitamin b-6 cialis soft tabs pharmacy software description of soma buy isoniazid cheap prevacid help ear infections on dog fat burning stop smoking remedies rhinitis treatment chronic pain relief birth control online meds without prescriptions buy lovastatin drug stores penis enlargement without pill cancer medicine buy deltasone cure for throat infection thyroid dogs dosage cipro viagra from uk cheap alcoholism treatment natural cure for constipation paxil cialis 5mg tablets amitriptyline uses topamax drugs lower heart rate drug discount codes dog medicines body fat loss joint pain recurring urinary tract infections ativan information buy drugs online cheap fast valium body building ambien maximum dosage information on valium how to sperm more chlamydia medication dosage buy cialis online viagra chest pain heart fluconazole interaction calcium channel blocker side effects zolpidem dosage online drug stores zelnorm muscle strength fluconazole buy stress gum free weight loss products information on gout low immune system online viagra cialis 20 buy cefixime phentermine from canada gain muscle mass fast lasix side effects buy singulair penis enlargement free natural muscle and joint health viagra online overnight cialis online aceon allergies and asthma diamox side effects weight loss software generic compazine price for tramadol high blood pressure symtoms osteoporosis help treatment severe constipation drug new smoking stop pain relief product xanax online dog health info clonazepam .5mg buy tribulus pregnancy prevention methods allergy hives