CS193p
Spring 2010
Monday, April 12, 2010
Announcements
Axess!
Make sure your grading option matches what you were approved for
Sonali’s Office Hours Changed
Friday 11am to 1pm
Thursday 10am to noon
Gates B26B
Any questions about the Homework?
Did everyone get the e-mail about entering numbers?
Monday, April 12, 2010
Communication
E-mail
Questions are best sent to cs193p@cs.stanford.edu
Sending directly to instructor or TA’s risks slow response.
Web Site
Very Important!
http://cs193p.stanford.edu
All lectures, assignments, code, etc. will be there.
This site will be your best friend when it comes to getting info.
Monday, April 12, 2010
Today’s Topics
Protocols and Delegates
Views
Core Graphics
Demo
Monday, April 12, 2010
Protocols
Very similar to @interface, but no implementation
@protocol Foo
- (void)doSomething;
@optional
- (int)getSomething;
@required
- (NSArray *)getManySomethings:(int)howMany;
@end
Classes then proclaim they implement a protocol
@interface MyClass : NSObject <Foo>
...
@end
Monday, April 12, 2010
Protocols
Declaring arguments to require a protocol
- (void)giveMeTheObject:(id <Foo>)anObjectImplementingFoo
Declaring variables to require a protocol
id <Foo> obj = [[MyClass alloc] init];
[obj doSomething]; // will not warn (and should be okay)
Compiler will warn of misbehavior
Class says it implements protocol Foo, but doesn’t implement required methods
Assigning an object which does not implement Foo to a variable like obj above
Passing an object which does not implement Foo through an argument
which requires it (like above)
Monday, April 12, 2010
Delegates
Used to “delegate” responsibility to other objects
Protocol defines what the responsibility is
Great way to maintain MVC but with flexibility
Oftentimes View objects do this
Will see example of this in demo
Very common paradigm in UIKit
Monday, April 12, 2010
Views
Rectangular area on screen
Draws and handles events in that rectangle
Hierarchical
Only one superview: - (UIView *)superview
Can have many (or zero) subviews: - (NSArray *)subviews
Subview order matters: those later in the array are on top of earlier
UIWindow
The UIView at the top of the view hierarchy
Only have one UIWindow in an iPhone application (it’s all about views)
Monday, April 12, 2010
View Hierarchy
Hierarchy often constructed in IB
Even custom views can be added to the hierarchy in IB
How to do it in code though?
- (void)addSubview:(UIView *)aView;
- (void)removeFromSuperview;
How to manage the “order” of subviews
- (void)insertSubview:(UIView *)sv atIndex:(int)index;
- (void)insertSubview:(UIView *)sv belowSubview:(UIView *)otherView;
- (void)insertSubview:(UIView *)sv aboveSubview:(UIView *)otherView;
Monday, April 12, 2010
Transparency of Views
What happens when views overlap?
Order of subviews list determines who’s in front,
but lower ones can “show through” transparent views on top of them
When you are drawing (covered later), you can
draw with transparency (partial or fully)
Default is fully opaque drawing
If you want to hide a view completely, you can
just set the hidden property to YES
No need to remove the view from the hierarchy to hide it
Monday, April 12, 2010
View Memory Mgmt
Superviews retain their subviews
Once you put a view into the hierarchy you can release your ownership
if you want
Note that we retain IBOutlet variables
But we don’t really need to as long as they are always in the hierarchy.
It’s more of a convention to retain them.
But be careful!
If you remove a view from the view hierarchy it may deallocate
immediately (no autorelease happens). So, retain it first, then call
removeFromSuperview.
Monday, April 12, 2010
Coordinates
CGFloat
Just a floating point number, but always use CGFloat for graphics.
CGPoint
C struct with two CGFloats in it: x and y.
Create with CGPointMake(x, y)
CGSize
C struct with two CGFloats in it: width and height.
Create with CGSizeMake(width, height)
CGRect
C struct with a CGPoint origin and a CGSize size.
Create with CGRectMake(x, y, width, height)
Monday, April 12, 2010
increasing x
Coordinates
(0,0)
Origin of View’s coordinate system is upper left
(250, 85)
Units are “pixels”
No matter what the dps of the screen is
View property bounds is the local coordinate space
self.bounds.origin: decide what it means for your view
self.bounds.size.width/height is how wide/tall your view is
Use this rectangle when you are inside the implementation of a view
View’s frame and center properties
center is the center of the View in its superview’s coordinates
frame is the smallest rectangle which will contain the view
increasing y
So is frame.size always the same as bounds.size? No: rotation.
Use center and frame to position/size the view in its superview.
Monday, April 12, 2010
140
, 65
View A
30 320
0,
22 0
5 5
0,
20
2
0
0
Vi
ew
320
View B’s bounds is ((0,0),(200,250)) B
View B’s frame is ((140,65),(320,320))
View B’s center is (300, 225)
Monday, April 12, 2010
Creating Views
Most often you create views in IB
Even though custom views are not IB, you drag out generic UIView
from the Library window, then use the Inspector to change the class
to your custom class
How do you create them in code?
- (id)initWithFrame:(CGRect)aRect is designated initializer
Example:
CGRect buttonRect = CGRectMake(20, 20, 120, 37);
UIButton *button = [[UIButton alloc] initWithFrame:buttonRect];
button.titleLabel.text = @”Do it!”;
[window addSubview:button];
[button release];
Monday, April 12, 2010
Custom Views
When do I want to create my own view?
I want to do my own drawing on screen
And/or I want to handle touch events
Create a subclass of UIView
To do your own drawing, implement drawRect:
- (void)drawRect:(CGRect)clipRect;
You can optimize by not drawing outside of clipRect, but not required
NEVER call drawRect: !! EVER!
Instead, let system know view is “out of date” and needs a redraw.
It will then call your drawRect: at an appropriate time.
- (void)setNeedsDisplay
- (void)setNeedsDisplayInRect:(CGRect)clipRect
Monday, April 12, 2010
Custom Views
To handle events, you must implement all of these
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event;
Or use a UIGestureRecognizer
We’ll talk about touches and gestures later
Monday, April 12, 2010
Drawing
How do you implement drawRect:?
Draw with Quartz2D
Quartz2D is part of Core Graphics Framework
It is a C API (not object-oriented)
Concepts
Get a context to draw into
Apply transformations
Create paths
Set colors, fonts, textures, linewidths, linecaps, etc.
Stroke or fill those paths
Monday, April 12, 2010
Context
Context determines where your drawing goes
Screen
Offscreen Bitmap
PDF
Printer
UIKit sets up a context for you in drawRect:
Only valid during that execution of drawRect:
So never cache the context!
You’ll get a new one each time
Get the context in drawRect: with this method
- (CGContextRef)UIGraphicsGetCurrentContext();
CGContextRef context = UIGraphicsGetCurrentContext();
Monday, April 12, 2010
Graphics State
Setup graphics state of the context
Many different properties, e.g., CGContextSetLineWidth(context, 1.0);
The context UIKit provides has sensible defaults
Colors have some object-oriented support in UIKit
UIColor *myColor = [UIColor blueColor];
UIColor *rgb = [UIColor colorWithRed:0.5 green:1.0 blue:0.125 alpha:1.0];
[myColor set];
[myColor setStroke];
[rgb setFill];
Monday, April 12, 2010
Define a Path
Begin the path
CGContextBeginPath(context)
Move around and add lines or arcs to the path
CGContextMoveToPoint(context, 75, 10);
CGContextAddLineToPoint(context, 10, 150);
CGContextAddLineToPoint(context, 160, 150);
Close the path (connects last point back to first)
CGContextClosePath(context); // not strictly required
Set any graphics state and then draw the path
[[UIColor greenColor] setFill]; [[UIColor redColor] setStroke];
CGContextDrawPath(context, kCGPathFillStroke);
Monday, April 12, 2010
Define a Path
It’s also possible to save paths and reuse them
See functions in the docs that start with CGPath instead of CGContext
Monday, April 12, 2010
Graphics State
Defining a method to draw something
What if that method sets graphics state?
It might “mess up” the graphics state of the calling method
You can “push” the current graphics state, then pop
UIGraphicsPushContext(context);
<do whatever you want with the graphics state>
UIGraphicsPopContext();
Monday, April 12, 2010
Drawing Text
Use UILabel, but if you feel you must ...
Object in UIKit to get a font
UIFont *myFont = [UIFont systemFontOfSize:12.0];
UIFont *theFont = [UIFont fontWithName:@”Helvetica” size:36.0];
NSArray *availableFonts = [UIFont familyNames];
Special methods in NSString to draw text
NSString *text = ...;
[text drawAtPoint:(CGPoint)p withFont:theFont];
CGSize textSize = [text sizeWithFont:myFont];
Check out NSString(UIStringDrawing) in docs
Monday, April 12, 2010
Drawing Images
Use UIImageView, but if you must ...
Create an image from a file in your Resources
UIImage *image = [UIImage imageNamed:@”foo.jpg”];
Create an image from a file or from raw data
UIImage *image = [[UIImage alloc] initWithContentsOfFile:(NSString *)path;
UIImage *image = [[UIImage alloc] initWithData:(NSData *)data];
Create an image using CGContext functions
UIGraphicsBeginImageContext((CGSize)size);
<draw with CGContext functions as usual>
UIImage *myImage = UIGraphicsGetImageFromCurrentContext();
UIGraphicsEndImageContext();
Monday, April 12, 2010
Drawing Images
Blasting the bits into the current context
UIImage *image = ...;
[image drawAtPoint:(CGPoint)p]; // p is upper left corner of image
[image drawInRect:(CGRect)rect]; // scales the image
[image drawAsPatternInRect:(CGRect)rect]; // tiles the image
Aside: You can get your UIImage as PNG or JPG
NSData *jpgData = UIImageJPGRepresentation((UIImage *)myImage);
NSData *pngData = UIImagePNGRepresentation((UIImage *)myImage);
Monday, April 12, 2010
Demo
UISlider
Custom View with drawRect:
Delegate
Quartz 2D
Monday, April 12, 2010
Wednesday
Application Structure & Lifecycle
Application Delegate
UINavigationController
Demo of AppDelegate and UINavigationController
Homework Explanation
Monday, April 12, 2010
Homework
Tomorrow at 11:59pm!
Monday, April 12, 2010