IPhone Programming Version 2 Created by Nathan Magnus.

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

View-Based Application Development Lecture 1 1. Flows of Lecture 1 Before Lab Introduction to the Game to be developed in this workshop Comparison between.
MS® PowerPoint.
Detecting Collisions CSE 391 Fall 2012 Tony Scarlatos.
Create a calculator– 2nd iPhone programming exercise CSE 391 Fall 2012.
Introduction to Objective-C and Xcode (Part 1) FA 175 Intro to Mobile App Development.
© by Pearson Education, Inc. All Rights Reserved.
Visual Basic 2010 How to Program. © by Pearson Education, Inc. All Rights Reserved.2.
Guide to Oracle10G1 Introduction To Forms Builder Chapter 5.
Anatomy of an iPhone Application Content taken from book: “iPhone SDK Development” by Bill Dudney and Chris Adamson.
View Controllers (second part) Content taken from book: “iPhone SDK Development” by Bill Dudney and Chris Adamson.
IPhone Development Crash Course By Dylan Harris
IPhone 101. Outline Objective-C Random bits of the API Using the simulator Debugging with Xcode.
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
Chapter 2: The Visual Studio.NET Development Environment Visual Basic.NET Programming: From Problem Analysis to Program Design.
Storyboards Managing multiple views. Overview Create a single view application Give the project a name and click “Use Storyboards” and “Use Automatic.
1 Introduction to Human Computer Interaction  Livecode Overview  Based on Livecode User Guide from RunRev Ltd. (2010) 
Microsoft Visual Basic 2010: Reloaded Fourth Edition Chapter One An Introduction to Visual Basic 2010.
Chapter 9 Introduction to ActionScript 3.0. Chapter 9 Lessons 1.Understand ActionScript Work with instances of movie clip symbols 3.Use code snippets.
Chapter 9 Collecting Data with Forms. A form on a web page consists of form objects such as text boxes or radio buttons into which users type information.
8 Copyright © 2004, Oracle. All rights reserved. Creating LOVs and Editors.
A First Program Using C#
Sprite Animation CSE 391 Fall 2012 Tony Scarlatos.
Chapter 3 Working with Symbols and Interactivity.
© 2011 Delmar, Cengage Learning Chapter 3 Working with Symbols and Interactivity.
Domain 3 Understanding the Adobe Dreamweaver CS5 Interface.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Appendix E The EZJava.
Objective C Basics. It’s C with Some Extras!  Cross Platform language  Mac  Linux/UNIX  Windows  Layer above C (Superset)  Adds Object-Oriented.
© 2010 Delmar, Cengage Learning Chapter 3: Working with Symbols and Interactivity.
Tabbed Views UITabBarController. Controller Architecture UITabBarController Controls the first view that the user sees The view controller class (and.
Navigation in iPads splitViewController. Overview Create a Master-Detail application Switch Device Family to iPad Give the project a name and click “Use.
IOS with Swift Hello world app.
Create a Web View App Step-by-Step. Step 1 Create a new project in XCode using the "Single View Application" option.
Chapter Two Creating a First Project in Visual Basic.
View Controllers Content taken from book: “iPhone SDK Development” by Bill Dudney and Chris Adamson.
Applications Development
Course Summary Xcode & iPhone Simulator
Nav Controllers UINavigationController. Overview Nav Controller basics Like a tabview controller, a navViewController manages views A navigationViewController.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
IPhone Programming Version 2 Created by Nathan Magnus.
Chapter 5 Introduction to Defining Classes
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Creating a Java Application and Applet
Lecture 10 Using Interface Builder to create Mac Applications.
The iOS Platform and SDK. iOS iPhoneiPad Mini iPad.
1 Reverse a String iPhone/iPad, iOS Development Tutorial.
Key Applications Module Lesson 22 — Managing and Reporting Database Information Computer Literacy BASICS.
Debugging tools in Flash CIS 126. Debugging Flash provides several tools for testing ActionScript in your SWF files. –The Debugger, lets you find errors.
Folio3 IPhone Training Session 2 Testing App on device Presenter: Imam Raza.
XP New Perspectives on Macromedia Dreamweaver MX 2004 Tutorial 5 1 Adding Shared Site Elements.
Integrating Components and Dynamic Text Boxes with the Animated Map– Lesson 101 Integrating Components and Dynamic Text Boxes with the Animated Map Lesson.
CIS 205—Web Design & Development Flash Chapter 3 Working with Symbols and Interactivity.
 2002 Prentice Hall. All rights reserved. 1 Introduction to the Visual Studio.NET IDE Outline Introduction Visual Studio.NET Integrated Development Environment.
Microsoft Visual Basic 2012: Reloaded Fifth Edition Chapter One An Introduction to Visual Basic 2012.
WebViews UIWebView. Controller Architecture UITabBarController Controls the first view that the user sees The view controller class (and xib) that manages.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Mind Mapping with Bubbl.us. The Bubbl.us Homepage Click to create a bubbl.us account Sign in or, To access, type
Chapter 2: The Visual Studio .NET Development Environment
iOS UI Components Sisoft Technologies Pvt Ltd
Chapter 1: An Introduction to Visual Basic 2015
Programming In Any Language With “Hello, World!” Examples
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
EEC-492/693/793 iPhone Application Development
CIS16 Application Development Programming with Visual Basic
Windows xp PART 1 DR.WAFAA SHRIEF.
Tutorial 6 Creating Dynamic Pages
Working with Symbols and Interactivity
EEC-492/693/793 iPhone Application Development
CSC 581: Mobile App Development
Presentation transcript:

iPhone Programming Version 2 Created by Nathan Magnus

Apple Your most useful resource is the Apple developer documentation. 

Xcode IDE Apple provides an IDE for creating iPhone applications Xcode can also be used to create OSX applications

Xcode IDE Installation  Download from You will need to create an account if you do not already have one  Mount by clicking on it in the download directory  Double click on iPhone SDK

iPhone Simulator Simulates an iPhone. Can be rotated by 90° to the right or left through the “Hardware” menu Supports multiple touches (option and option-shift) Known bugs:  Cannot be rotated upside down  When rotated there is a small area that will not respond to touches

An IPhone Application Create an application that loads Google in a UIWebView –The user enters a URL into the text field and when they click enter on the keyboard the UIWebView loads that address

Creating the Program Create a new View-Based application in Xcode –File -> New Project... –Select “View-Based Application” and click “Choose...” –Name your project “webNav” and save

Program 1 In the upper pane, double click on webNavViewController.xib –This will open the interface builder (IB)

Program 1 Ensure the Library window is open (Tools-> Library)

Program 1 –Under Data View drag and drop a “Web View” onto the main view

Program 1

Click on webNavViewController.h in Xcode

Add the following lines of code –Under webNavViewController : UIViewController {“ Add “IBOutlet UIWebView *webView;” –Under “}” before Add (nonatomic, retain) UIWebView *webView;” Program 1

Return to the Interface Builder Click on the WebView in the main View Program 1

Ensure that the Connections Inspector is open (Tools -> Connections Inspector) Program 1

Click on the circle beside “New Referencing Outlet” and drag to “File’s Owner” Program 1

Select “webView” from the two options Program 1

Save the Interface Builder Double Click on webNavViewcontroller.m Program 1

Uncomment “-(void)viewDidLoad” function Program 1

Under [super viewDidLoad]; –Create a NSURL NSURL *url = [NSURL –The makes the following string a NSString –Create a NSURLRequest NSURLRequest *request = [NSURLRequest requestwithURL:url]; –Load the request [webView loadRequest:request]; Program 1

This is what the program should look like

Information Files (.m files can be renamed to.mm to allow Objective-C++):  ProjectNameAppDelegate (.h and.m) - Creates the window and view  ProjectNameViewController (.h and.m) - Controls user interaction with the view viewDidLoad is called when the initial view loads

 Create an application that has a UITextField, UILabel, UIButton and UIImageView –Screen begins with an image of a your handsome/beautiful instructor (or a hated celebrity), a UITextField and a UIButton (with an appropriate title) –The user enters a phrase into a UITextField. After they are done editing they can click on a UIButton.  If the phrase they entered matches a certain phrase then the image changes to an explosion and a label appears telling the user they just blew up the instructor.  If the phrase does not match, a message telling them to try again should be displayed. Program 2

Steps: 1.Find an image of your handsome/beautiful instructor or a hated celebrity and save it to “Documents” 2.Find an image of an explosion and save it to “Documents” 3.Create a new View-Based Application (call it “Boom” 4.Create the Interface using IB 1.Add a UILabel (found in Inputs & Values) 2.Add a UIImageView (found in Data Views) 3.Add a UITextField (found in Inputs & Values) –Top half of screen due to onscreen keyboard 4.Add a UIButton (found in Inputs & Values)

Program 2

Click on the Attributes Inspector tab (or Tools->Attributes Inspector) Program 2

Select the button and add the title “Check Input”

Navigate to your saved image using Finder Drag and drop your images into the “Resources” group of the Xcode project Program 2

Select “Copy items into destination group’s folder (if needed) and ensure other settings are all defaults then click “Add”

Program 2

Click on the UIImageView in the IB and add your image in the Attributes Inspector Program 2

Open the Connection Inspector (Tools->Connections Inspector) Select each object on the interface builder (UITextField, UIButton, UIImageView, UILabel), drag to “File’s Owner” and select the appropriate option For the UITextField, click on the circle beside “delegate” and drag to “File’s Owner” Program 2

Add to BoomViewController.h –After BoomViewController : UIViewController {“ IBOutlet UILabel *label; IBOutlet UITextField *input; IBOutlet UIImageView *image; IBOutlet UIButton *button; Program 2

–After “}” (nonatomic, retain) UILabel (nonatomic, retain) UITextField (nonatomic, retain) UIImageView (nonatomic, retain) UIButton *button; -(BOOL)textFieldShouldReturn: (UITextField*)theTextField; -(void)checkInput; Program 2

In BoomViewController.m –Uncomment the “–(void)viewDidLoad” method –Add after “[super viewDidLoad];” [label the detonation code.”]; [button addTarget:self forcontrolEvents:UIControlEventTouchUpInside]; Program 2

–Add after the “–(void)viewDidLoad” function -(BOOL)textFieldShouldReturn: (UITextField*)theTextField { [theTextField resignFirstResponder]; return YES; } Program 2

–Add after the “-(void)viewDidLoad” method -(void)checkInput { NSString *userInput = [input text]; if([userInput =NSOrderedSame) { [label instructor went BOOM!”]; [image setImage:[UIImage } else { [label setText:[NSString stringWithCString:“That is not the correct detonation code.”]]; [image setImage:[UIImage } Program 2

Finished Product:

Program 2

NSArray Used to hold objects in an array id is the default object type. All objects (NSUInteger, NSString, etc) can be passed as an id Initializing:  +(id)arrayWithObjects:(id)obj1, (id)obj2,…,nil - nil terminated list of objects to be added to the array Accessing:  -(id)objectAtIndex:(NSUInteger)index - return the id of the object at the given index Functions also exist for sorting, comparing and obtaining information about the array

Objective-C Variables:  Types include char, int, unsigned, float, double, BOOL  Constants declared using “const” keyword  declared by: type name; Ex) float floatVal ; char character; Conditional structures:  if(condition) { code }  else if(condition) { code }  else (condition) { code }  switch (condition) { case constant: code break; default break; } == Equal <= Less or Equal >= Greater or Equal < Less > Greater != Not Equal Comparison Operators

Objective-C Loops:  do { code } while(condition);  while(condition) { code }  for(initialize; condition; increment) { code } Arrays:  Declaration: type name[sizeOfArray];  Initialize: type name[] = {value1, value2 name[0]=value1; name[1]=value2; Pointers:  Objects when using [Object method]; must be pointers or class name  Initialize: type * name; nil / null - indicates no object at pointer but if used will not cause crash

Example of Objective-C -(void)method { const unsigned loopAmt = 10; printf("Testing: "); for(unsigned i=0; i<loopAmt; i++) printf("%i...", i); //prints “Testing:0…1…2…3…4…5…6…7…8…9… }

Exercise  1) Create a web navigation application with UITextField and UIWebView The user enters a URL into the text field and when they click enter on the keyboard the UIWebView loads that address  2) Create a simple game of Tic Tac Toe Different status messages should be displayed on the screen (most likely using a UILabel) When a game ends, nothing can be pushed except a button that asks if the user would like to play again

Objective-C Classes Interface declared by ClassName:SuperClass ” and ended by ” SuperClass must always be “Object” or a subclass of “Object” (NSObject for the iPhone) Implementation declared by ClassName” All class methods are public Instance variables are private by default Classes can be extended with categories (no example will be given)

Example of Classes //tempClass inherits from tempClass : NSObject int var; //private instance variable } //function prototypes +(int)staticMethod; //end of interface

Example of tempClass +(int)staticMethod { var = 200; return var; } -(int)method { var = 100; //assign a value to var return var; //return value of var

Objects Since every object must extend the NSObject class (or a subclass of it) to create a new object call the “alloc” method  Ex) tempClass *tc = [tempClass alloc]; If a method is static, it can be called without allocating the object  Ex) [tempClass staticMethod];

Objective-C++ Syntax almost identical to Objective-C Allows the use of C++ libraries and functions (ie:, ).h extension for header files and.mm extension for implementation files

Example of Objective-C++ #include -(int)getInteger { return 5; } int aFunction(id this2) { /*print the value returned by the getInteger function of the object passed to the method*/ cout << [this2 getInteger]; return 10; }

Info.plst Info.plst file contains information about your project  Application icon (must be included as a resource)  Main nib file

NSString Full list of functions and properties can be found at: “ on/Classes/NSString_Class/Reference/NSString.html” Creating:  Add in front of a regular string World!”  [NSString stringWithCString:“Hello World!”];  Many other methods including from file and URL Methods:  length, lowercaseString, uppercaseString, capitalizedString, compare:(NSString*)aString NSOrderedAscending, NSOrderedSame, NSOrderedDescending

Common Information hidden - whether the object is visible or not Ex) label.hidden = NO; userInteractionEnabled - whether the object will respond to a touch or not Ex) label.userInteractionEnabled = YES; center - CGPoint representing the center of the object (CGPoint is a struct with x and y fields) Ex) cout << label.center.x;

UIButton Found in IB library under Inputs & Values Setters:  setBackgroundImage:(UIImage*) forState:(UIControlState)  setImage:(UIImage*) forState:(UIControlState)  setTitle:(NSString*) forState:(UIControlState) Properties:  currentTitle, currentTitleColor, currentImage, currentBackgroundImage, hidden Ex) aButton.hidden = YES ;

UIImageView Found in IB library under Data Views Initializers:  initWithImage:(UIImage*) [UIImage imageNamed:(NSString*)name] is useful Properties:  image, userInteractionEnabled, hidden

UITextView Found in IB library under Data Views UITextAlignment - UITextAlignmentRight, UITextAlignmentLeft, UITextAlignmentCenter. UIColor allows allows for creation of custom colors as well as presets such as greyColor, redColor, greenColor, etc Properties:  text, font, textColor, editable, textAlignment, hidden

UITextField Found in IB library under Inputs & Values Properties:  text, font, textColor, textAlignment, hidden

Closing the Keyboard Keyboard automatically displays on the lower half of the screen when a field that allows input is touched Keyboard does not automatically close  Must set the delegate (via the IB connection manager window) for the textView, textField or other object that brings up the keyboard to “File’s Owner”  //when return is touched on the keyboard, this is called (BOOL)textFieldShouldReturn: (UITextField*)theTextField { [theTextField resignFirstResponder]; return YES; }

UILabel Found in IB library under Inputs & Values Properties:  text, font, textColor, textAlignment, enabled, adjustsFontSizeToFitWidth, minimumFontSize, numberOfLines, highlightedTextColor, hidden

NSURL/NSURLRequest NSURL Functions:  URLWithString:(NSString*)string  initWithString:(NSString*)string  URLWithString:(NSString*)string relativeToURL:(NSURL*)url  initWithString:(NSString*)string relativeToURL:(NSURL*)url NSURLRequest Functions:  initWithURL:(NSURL*)url

UIWebView Found in IB library under Data Views Properties:  canGoBack, canGoForward, loading Methods:  goBack, goForward, stopLoading, reload, loadRequest:(NSURLRequest*)request

Creation Without IB All UI Objects can be created without using the IB  Create a CGRect variable to hold the object using CGRectMake(x-offset, y-offset, width, height) Ex) CGRect r = CGRectMake(20.0, 20.0, 100.0, 40.0);  Allocate the memory for and initialize the object using initWithFrame: Ex) UILabel *label = [[UILabel alloc] initWithFrame:r];  Set object specific properties Ex) [label Created”];  Add to the appropriate view Ex) [self addSubview:label];

Selectors Selectors are written into a table and used at runtime to reference a method Class methods and instance methods with the same name would be assigned the same selector directive allows the programmer to refer to a compiled selector rather than method name To define a selector use SEL Ex) SEL aSelector Other methods can be used to get selector information  NSSelectorFromString(NSString)  NSStringFromSelector(SEL)

Selectors Methods that use Selectors  performSelector:(SEL)  performSelector:(SEL) withObject:(id)  performSelector:(SEL) withObject:(id) withObject:(id)

Selector Example -(void)method2:(int)i int2:(int)j { //outputs “12” to the debug console cout << [i intValue] << [j intValue]; } -(void)method { NSNumber* i = [NSNumber numberWithInt:1]; NSNumber* j = [NSNumber numberWithInt:2]; SEL s [self performSelector:s withObject:i withObject:j]; //outputs “method2:int2:” to debug console cout << [NSStringFromSelector(s) cString]; }

Add a Target Method Can add an action to a UI object when it is touched  [backButton addTarget:webView forControlEvents:UIControlEventTou chUpInside];

Multiple Views with IB Multiple views in Interface Builder can be displayed and hidden by their “ hidden ” property Multiple windows can be displayed and hidden by their “ hidden ” property

Touches Four functions can be overwritten (in EAGLView or ProjectNameViewController)  -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event - Called when finger(s) touch the display  -(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event - Called when finger(s) are moved on the display  -(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event - Called when fingers(s) are removed from the display  -(void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event - Called if the system interrupts your application

Using Touches In order for information about multiple touches to be passed, must set “ self.multipleTouchEnabled = YES; ” The function’s parameters can be used to get information about the touches [[touches allObjects] objectAtIndex:0] - will return the id of the first touch on the display.  This id can be used to call the locationInView:self function which returns a CGPoint struct (holds x and y coordinates)

Example of Multiple Touches -(void) touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { CGPoint touch; int touchCount = [[event allTouches] count]; self.multipleTouchEnabled = YES; for(int i=0; i<touchCount; i++) { touch = [[[touches allObjects]objectAtIndex:i] locationInView:self]; printf("Touch #%i at (%f,%f)\n", i+1, touch.x, touch.y); }

Orientation iPhone has built in accelerometer that can be used to determine orientation Need to turn orientation notifications on  [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotification s]; Can access by accessing [UIDevice currentDevice].orientation  0 represents state unknown ( UIDeviceOrientationUnknown)  1 represent upright state in simulator ( UIDeviceOrientationPortrait)  3 represents landscape view with left side down ( UIDeviceOrientationLandscapeLeft)  4 represents landscape view with right side down ( UIDeviceOrientationLandscapeRight)

Exercise Create a program that draws 2 shapes. These shapes will move toward the new bottom of the screen if it is rotated.

Exercise Create a program that draws a textured shape in the middle of the screen  If two fingers are moved in parallel the image moves in the direction of the fingers’ movement  If two fingers move apart or towards each other the shape is enlarged or shrunk

Exercise Create a program that draws a shape. Every 0.2 seconds the object moves to right, left, up or down.  Use touch events to control the direction that the object moves

OpenGL ES Application Draw, rotate and move shapes Change colors and sizes at run-time Files (.m files can be renamed to.mm to allow Objective-C++)  EAGLView (.h and.m) - Already imports OpenGL ES library -(void)drawView - is called every animationInterval seconds Other Functions already given include startAnimation, stopAnimation, setAnimationInterval, setAnimationTimer, dealloc, createFramebuffer, destroyFramebuffer and initWithCoder  ProjectNameAppDelegate (.h and.m) - Creates the window and view

NSTimer Useful class that is frequently used to call a method periodically based on time Methods  [NSTimer scheduledTimerWithTimeInterval:(flo at seconds) target:(id target) name) userInfo:nil repeats:(YES or NO)];

OpenGL ES Some important OpenGL ES functions  glEnable(capability) and glDisable(capability) - enable or disable the capabilities declared by a constant GL_TEXTURE_2D - allow textures to be mapped to 2D objects GL_LIGHTING - allow lighting to modify colors GL_FOG - blend a fog color into the post texturing color GL_BLEND - allows for transparency

OpenGL ES  glClientEnableState(capability) and glClientDisableState(capability) - enable and disable a capability GL_VERTEX_POINTER - vertices of an object are defined by an array of points GL_COLOR_POINTER - colors at vertices are defined by an array of points GL_TEXTURE_COORD_POINTER - map texture coordinates in an array to the texture

OpenGL ES  glTranslatef(x, y, z) - move the object on the coordinate plane by x, y and z  glRotatef(x, y, z) - rotate the object around the line defined by x, y and z  glDrawArrays(mode, first, count) mode - the way to draw the object  GL_TRIANGLE_FAN, GL_TRIANGLE_STRIP, GL_LINE_LOOP, GL_LINES first - the element in the array that represents the first point count - the number of points in the array

OpenGL ES  glBlendFunc(sfactor, dfactor) sfactor - specifies how RGBA source blending computed (use GL_SRC_ALPHA) dfactor - specifies how RGBA destination blending computed (use GL_ONE_MINUS_SRC_ALPHA)  glTexEnvf(target, pname, param) / glTexEnvi(target,pname,param) target - specifies the texture environment (GL_TEXTURE_ENV) pname - single valued texture environment parameter (GL_TEXTURE_ENV_MODE) param - symbolic constant (GL_DECAL)

OpenGL ES  glVertexPointer(dimensions, type, stride, vertexPointer)  glColorPointer(values, type, stride, colorPointer)  glColor4f(red, green, blue, alpha) / glColor4ub(red, green, blue, alpha)  glTexCoordPointer(dimensions, type, texturePointer)  glBindTexture(type, texture)

OpenGL ES  glMatrixMode(type) - the type of view being worked with GL_MODELVIEW - Position of the model relative to the screen GL_PROJECTION - View seen on the screen  glPushMatrix() - save the current view to a stack  glPopMatrix() - retrieve the last view that was pushed onto the stack  glLoadIdentity() - replaces the current matrix with the identity matrix (resets to defaults)

OpenGL ES  glOrthof(xMin, xMax, yMin, yMax, zMin, zMax) - set up the coordinate plan xMin - the lowest x value visible xMax - the highest x value visible yMin - the lowest y value visible yMax - the highest y value visible zMin - the lowest z value visible zMax - the highest z value visible

Load Textures -(void)loadTexture:(NSString *)name intoLocation:(GLuint)location { CGImageRef textureImage = [UIImage imageNamed:name].CGImage; if (textureImage == nil) { //If the image doesn’t exist, print an error to load texture image"); return; } NSInteger texWidth = CGImageGetWidth(textureImage); //get the width NSInteger texHeight = CGImageGetHeight(textureImage); //get the height GLubyte *textureData = (GLubyte *)malloc(texWidth * texHeight * 4); CGContextRef textureContext = CGBitmapContextCreate(textureData,texWidth, texHeight,8, texWidth * 4, CGImageGetColorSpace (textureImage), kCGImageAlphaPremultipliedLast); CGContextTranslateCTM(textureContext, 0, texHeight); CGContextScaleCTM(textureContext, 1.0, -1.0); CGContextDrawImage(textureContext, CGRectMake(0.0, 0.0, (float)texWidth, (float)texHeight), textureImage); CGContextRelease(textureContext); glBindTexture(GL_TEXTURE_2D, location); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData); free(textureData); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); }

glScale glScalef(GLfloat x, GLfloat y, GLfloat x) glScaled(GLdouble x, GLdouble y, GLdouble z)  Scale the current view matrix by x, y and z

Example float vertices[] ={ 1, 1, 0, 0, 0, 1 }; glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glTranslatef(5, 5, 0); glScalef(0.5, 0.5, 0); glVertexPointer(2, GL_FLOAT, 0, vertices); glEnableClientState(GL_VERTEX_ARRAY); glColor4ub(255, 255,51, 128); glDrawArrays(GL_TRIANGLE_STRIP, 0, 6); glPopMatrix(); glDisable(GL_BLEND);

Exercise Create an application that draws 2 shapes which will bounce off the sides of the screen and each other. Add a texture and vector physics to this shape if you need more of a challenge. Create an application that draws stars in the top half of the screen.  Each star has a random rotation and location on the screen. The star will change a combination of size, color, transparency or rotation periodically to simulate twinkling.

Memory Management If instance created by [Object alloc ] message or malloc(size) C function it will not be automatically released. Each of these calls (as well as every time retain is called) increments the retain count. Methods of releasing data (releasing the object reduces its retain count) release – [ObjectVariable release ]; autorelease - [ObjectVariable autorelease ]; (if makes retain count 0, ensures object is not going to be referenced. Generally object is released at end of function/current scope) dealloc () is called when object’s retain count is 0 (similar to C++ destructor)  Release all appropriate instance variables in dealloc

Objective-C Classes Interface declared by ClassName:SuperClass ” and ended by ” SuperClass must always be “Object” or a subclass of “Object” (NSObject for the iPhone) Implementation declared by ClassName” All class methods are public Instance variables are private by default Classes can be extended with categories (example later)

Objective-C Used as default language in xcode Can run almost all c programs.h extension for header files and.m extension for implementation files Methods in same class referenced using self (similar to the “this” keyword in c++) Syntax:  Default return type is ‘id’  Message: [Object function:arg1 parameter2:arg2]; (similar to Object->function(arg1, arg2);)  -(returnType)function:(type)arg1 parameter2:(type)arg2 { code }  +(returnType)staticFunction:(type)arg1 parameter2:(type)arg2 { code }

Extending Classes // A class tempClass (Category) // New methods  (BOOL) tOrF;  tempClass(Category)  (BOOL) tOrF {…}  (void)

Creating an iPhone Project “File->New Project…” Options we will discuss:  OpenGL ES Application  View-Based Application  Tab Bar Application

Example of Objective-C - (void)viewDidLoad { [super viewDidLoad]; [self fnWithInt]; }

Objective-C -(void)fnWithInt:(int)i int2:(int)j  Method name - “fnWithInt:int2:” C can call Objective-C functions and Objective-C can call C functions. “ self ” can not be used from C functions  Work around this by creating a global variable or passing type id

Objective-C Called by C -(int)getInteger { return 5; } int aFunction(id this2) { /*print the value returned by the getInteger function of the object passed to the method*/ printf("%i", [this2 getInteger]); return 10; }

- used to automatically create missing getters (cd) and setters (setCd:) function for an instance variable Synthesized variables must have an  (retain) UIDevice cd; //creates 2 methods: “cd” and cd; … //set cd to the current device using the synthesized method [self setCd:[UIDevice currentDevice]];

( parameters ) type name:  nonatomic - allows more than one thread to access a getter/setter at a time  atomic - only allow one thread to access a getter/setter at a time (default)  retain - setter should use “retain” in the variable assignment (ex: var1 = [var2 retain]; ) Used for objects  assign - setter will assign directly to the variable Used for basic variable types  readonly - setter will not be generated