24
7/28/2019 Lecture 4 Slides (October 6, 2011) http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 1/24 Stanford CS193p Developing Applications for iOS Fall 2011

Lecture 4 Slides (October 6, 2011)

Embed Size (px)

Citation preview

Page 1: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 1/24

Stanford CS193pDeveloping Applications for iOS

Fall 2011

Page 2: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 2/24

ViewsA view (i.e. UIView subclass) represents a rectangular aDefines a coordinate space

Draws and handles events in that rectangle

HierarchicalA view has only one superview - (UIView *)superview

But can have many (or zero) subviews - (NSArray *)subviews

Subview order (in subviews array) matters: those later in the array are on top of

UIWindowThe UIView at the top of the view hierarchyOnly have one UIWindow (generally) in an iOS application

It’s all about views, not windows

Page 3: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 3/24

ViewsThe hierarchy is most often constructed in Xcode grapEven custom views are added to the view hierarchy using Xcode (more on this lat

But it can be done in code as well- (void)addSubview:(UIView *)aView;

- (void)removeFromSuperview;

Page 4: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 4/24

View CoordinatesCGFloat Just a floating point number, but we always use it for graphics.

CGPointC struct with two CGFloats in it: x and y.CGPoint p = CGPointMake(34.5, 22.0); p.x += 20; // move right by 20 points

CGSizeC struct with two CGFloats in it: width and height.CGSize s = CGSizeMake(100.0, 200.0); s.height += 50; // make the size 50 points taller

CGRectC struct with a CGPoint origin and a CGSize size.CGRect aRect = CGRectMake(45.0, 75.5, 300, 500); aRect.size.height += 45; // make the rectangle 45 points talleraRect.origin.x += 30; // move the rectangle to the right 30 points

Page 5: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 5/24

(0,0)

    i                                                                                                                                                                                               n                                                                                                                                       c                                                                                                                                           

      r                                                                                                                                            e                                                                                                                                       a                                                                                                                                         s                                                                                                                                                i                                                                                                                                                                                               n                                                                                                                                     

                                                                          g                                                                                                                                

                                                                y                                                                                                                                       

CoordinatesOrigin of a view’s coordinate system is upper left

Units are “points” (not pixels)Usually you don’t care about how many pixels per point are on the screen you’re Fonts and arcs and such automatically adjust to use higher resolution.However, if you are drawing something detailed (like a graph, hint, hint), you mightThere is a UIView property which will tell you:@property CGFloat contentScaleFactor; // returns pixels per point on the screeThis property is not (readonly), but you should basically pretend that it is for th

Views have 3 properties related to their location and s@property CGRect bounds; // your view’s internal drawing space’s origin and siThe bounds property is what you use inside your view’s own implementation.It is up to your implementation as to how to interpret the meaning of bounds.ori@property CGPoint center; // the center of your view in your superview’s coo@property CGRect frame; // a rectangle in your superview’s coordinate space  // contains your view’s bounds.size

(400, 35)

Page 6: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 6/24

CoordinatesUse frame and center to position the view in the hieraThese are used by superviews, never inside your UIView subclass’s implementation

You might think frame.size is always equal to bounds.size, but you’d be wrong ..

View A

V  i  e w   B  

320

320

1 4 0 , 6 5 

View B’s bounds = ((0,0),(200

View B’s frame = ((140,65),(32

View B’scenter

=(300,225)

View B’s middle in its own coord(bound.size.width/2+bounds.o

bounds.size.height/2+bounds

which is (100,125) in this case

Because views can be rotated(and scaled and translated too

Views are rarely rotated, but dmisuse frame or center by ass

Page 7: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 7/24

Creating ViewsMost often you create views in XcodeOf course, Xcode’s palette knows nothing about a custom view class you might cre

In that case, you drag out a generic UIView from the palette and use the Inspecto change the class of the UIView to your custom class (demo of this later).

How do you create a UIView in code (i.e. not in Xcode)? Just use alloc and initWithFrame: (UIView’s designated initializer).

ExampleCGRect labelRect = CGRectMake(20, 20, 50, 30); UILabel *label = [[UILabel alloc] initWithFrame:labelRect]; label.text = @”Hello!”; [self.view addSubview:label];  // we’ll talk about self.view later  // (it is a Controller’s top-level view)

Page 8: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 8/24

Custom ViewsWhen would I want to create my own UIView subclass?I want to do some custom drawing on screen.

I need to handle touch events in a special way (i.e. different than a button or slidWe’ll talk about handling touch events later. For now we’re focussing on drawing.

Drawing is easy ... create a UIView subclass & override- (void)drawRect:(CGRect)aRect; You can optimize by not drawing outside of aRect if you want (but not required).

NEVER call drawRect:!! EVER! Or else!Instead, let iOS know that your view’s visual is out of date with one of these UIV

- (void)setNeedsDisplay; - (void)setNeedsDisplayInRect:(CGRect)aRect; It will then set everything up and call drawRect: for you at an appropriate timeObviously, the second version will call your drawRect: with only rectangles that n

Page 9: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 9/24

Custom ViewsSo how do I implement my drawRect:?Use the Core Graphics framework

The API is C (not object-oriented)

ConceptsGet a context to draw into (iOS will prepare one each time your drawRect: is calCreate paths (out of lines, arcs, etc.)Set colors, fonts, textures, linewidths, linecaps, etc.

Stroke or fill the above-created paths

Page 10: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 10/24

ContextThe context determines where your drawing goesScreen (the only one we’re going to talk about today)

Offscreen BitmapPDFPrinter

For normal drawing, UIKit sets up the current contextBut it is only valid during that particular call to drawRect:

A new one is set up for you each time drawRect: is calledSo never cache the current graphics context in drawRect: to use later!

How to get this magic context?Call the following C function inside your drawRect: method to get the current graCGContextRef context = UIGraphicsGetCurrentContext(); 

Page 11: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 11/24

Define a PathBegin the pathCGContextBeginPath(context);

Move around, add lines or arcs to the path CGContextMoveToPoint(context, 75, 10);

CGContextAddLineToPoint(context, 160, 150);

Page 12: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 12/24

Define a PathBegin the pathCGContextBeginPath(context);

Move around, add lines or arcs to the path CGContextMoveToPoint(context, 75, 10);

CGContextAddLineToPoint(context, 160, 150);

CGContextAddLineToPoint(context, 10, 150);

Page 13: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 13/24

Define a PathBegin the pathCGContextBeginPath(context);

Move around, add lines or arcs to the path 

Close the path (connects the last point back to the firCGContextClosePath(context); // not strictly required

CGContextMoveToPoint(context, 75, 10);

CGContextAddLineToPoint(context, 160, 150);

CGContextAddLineToPoint(context, 10, 150);

Page 14: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 14/24

Define a PathBegin the pathCGContextBeginPath(context);

Move around, add lines or arcs to the path 

Close the path (connects the last point back to the firCGContextClosePath(context); // not strictly required

Actually the above draws nothing (yet)!You have to set the graphics state and then fill/stroke the above path to see any

CGContextMoveToPoint(context, 75, 10);

CGContextAddLineToPoint(context, 160, 150);

CGContextAddLineToPoint(context, 10, 150);

Page 15: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 15/24

Define a PathBegin the pathCGContextBeginPath(context);

Move around, add lines or arcs to the path 

Close the path (connects the last point back to the firCGContextClosePath(context); // not strictly required

Actually the above draws nothing (yet)!You have to set the graphics state and then fill/stroke the above path to see any

CGContextMoveToPoint(context, 75, 10);

CGContextAddLineToPoint(context, 160, 150);

CGContextAddLineToPoint(context, 10, 150);

CGContextDrawPath(context, kCGPathFillStroke); // kCGPathFillStroke is a co

[[UIColor greenColor] setFill]; // object-oriented convenience method (more[[UIColor redColor] setStroke]; 

Page 16: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 16/24

Define a PathIt is also possible to save a path and reuse itSimilar functions to the previous slide, but starting with CGPath instead of CGCont

We won’t be covering those, but you can certainly feel free to look them up in th

Page 17: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 17/24

Graphics StateUIColor class for setting colorsUIColor *red = [UIColor redColor]; // class method, returns autoreleased in

UIColor *custom = [[UIColor alloc] initWithRed:(CGFloat)red // 0.0 to blue:(CGFloat)blue green:(CGFloat)green alpha:(CGFloat)alpha]; // 0.0 to

[red setFill]; // fill color set in current graphics context (stroke color not set)[custom set]; // sets both stroke and fill color to custom (would override [red

Drawing with transparency in UIViewNote the alpha above. This is how you can draw with transparency in your drawRe

UIView also has a backgroundColor property which can be set to transparent valuBe sure to set @property BOOL opaque to NO in a view which is partially or fully tIf you don’t, results are unpredictable (this is a performance optimization propertyThe UIView @property CGFloat alpha can make the entire view partially transpar

Page 18: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 18/24

View TransparencyWhat happens when views overlap?As mentioned before, subviews list order determine’s who’s in front

Lower ones (earlier in subviews array) can “show through” transparent views on t

Default drawing is opaqueTransparency is not cheap (performance-wise)

Also, you can hide a view completely by setting hidden@property (nonatomic) BOOL hidden; myView.hidden = YES; // view will not be on screen and will not handle ev

This is not as uncommon as you might thinkOn a small screen, keeping it de-cluttered by hiding currently unusable views mak

Page 19: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 19/24

Graphics StateSome other graphics state set with C functions, e.g. ...CGContextSetLineWidth(context, 1.0); // line width in points (not pixels)

CGContextSetFillPattern(context, (CGPatternRef)pattern, (CGFloat[])compone

Page 20: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 20/24

Graphics StateSpecial considerations for defining drawing “subroutinesWhat if you wanted to have a utility method that draws something

You don’t want that utility method to mess up the graphics state of the calling meUse push and pop context functions.

- (void)drawRect:(CGRect)aRect { CGContextRef context = UIGraphicsGetCurrentContext(); [[UIColor redColor] setFill]; // do some stuff [self drawGreenCircle:context]; // do more stuff and expect fill color to be red

}

- (void)drawGreenCircle:(CGContextRef)ctxt { UIGraphicsPushContext(ctxt);  [[UIColor greenColor] setFill]; // draw my circleUIGraphicsPopContext(); 

}

Page 21: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 21/24

Drawing TextUse UILabel to draw text, but if you feel you must ...

UseUIFont

object inUIKit

to get a fontUIFont *myFont = [UIFont systemFontOfSize:12.0];

UIFont *theFont = [UIFont fontWithName:@“Helvetica” size:36.0];

NSArray *availableFonts = [UIFont familyNames];

Then use special NSString methods to draw the textNSString *text = ...; [text drawAtPoint:(CGPoint)p withFont:theFont]; // NSString instance method

How much space will a piece of text will take up when drawn?CGSize textSize = [text sizeWithFont:myFont]; // NSString instance method

You might be disturbed that there is a Foundation method for drawing (which is But actually these NSString methods are defined in UIKit via a mechanism called Categories are an Objective-C way to add methods to an existing class without sWe’ll cover how (and when) to use this a bit later in this course.

Page 22: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 22/24

Drawing ImagesUse UIImageView to draw images, but if you feel you mWe’ll cover UIImageView later in the course.

Create a UIImage object from a file in your ResourcesUIImage *image = [UIImage imageNamed:@“foo.jpg”];

Or create one from a named file or from raw data(of course, we haven’t talked about the file system yet, but ...)UIImage *image = [[UIImage alloc] initWithContentsOfFile:(NSString *)fullP

UIImage *image = [[UIImage alloc] initWithData:(NSData *)imageData]; 

Or you can even create one by drawing with CGContextUIGraphicsBeginImageContext(CGSize);  // draw with CGContext functionsUIImage *myImage = UIGraphicsGetImageFromCurrentContext(); UIGraphicsEndImageContext();  

Page 23: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 23/24

Drawing ImagesNow blast the UIImage’s bits into the current graphicsUIImage *image = ...;

[image drawAtPoint:(CGPoint)p]; // p is upper left corner of the [image drawInRect:(CGRect)r]; // scales the image to fit in r

[image drawAsPatternInRect:(CGRect)patRect; // tiles the image into patRect

Aside: You can get a PNG or JPG data representation oNSData *jpgData = UIImageJPEGRepresentation((UIImage *)myImage, (CGFloat)q

NSData *pngData = UIImagePNGRepresentation((UIImage *)myImage); 

Page 24: Lecture 4 Slides (October 6, 2011)

7/28/2019 Lecture 4 Slides (October 6, 2011)

http://slidepdf.com/reader/full/lecture-4-slides-october-6-2011 24/24

Next TimeTomorrowSource Control

Next WeekProtocols (a little more Objective C)Demo of custom UIViewView Controller LifecycleControllers of ControllersStoryboardingUniversal Applications