菜单

斯坦福CS193P

C04

Views

UIView 是所有控件的根類,

UIWindow 是iOS 應用的View 樹的根節點

添加View 到父View 調用的是父View的方法,將View移除用的是這個View本身的方法

- (void)addSubview:(UIView *)aView;
- (void)removeFromSuperview;

View 的數值用的是 CGFloat,屏幕上的點用的是 CGPoint ,面積用的是 CGSize ,屏幕上的矩形用的是CGRect

iOS 在屏幕上的單位用的是point 而不是pixel,point 應該是設備無關的單位

@property CGFloat contentScaleFactor;

這個屬性提供point 到 pixel 的轉換

view 還有3個屬性來定義它的位置和大小

@property CGRect bounds; // view 的內部大小,就是可繪製的空間。起始點總是{0,0}
@property CGPoint center; // view 的中點在父view 的座標
@property CGRect frame;  // view 在 父view 佔用的空間

View 的繪製方法

- (void)drawRect:(CGRect)aRect; // 由系統調用

View 用 Core Graphics Framework 來繪製圖形。C的api,不是面向對象的。

- (void)drawRect:(CGRect)rect
{
    CGContextRef context = UIGraphicsGetCurrentContext(); //獲取繪製上下文,可以是View,Printer,離屏圖像,PDF等等,跟Android 的Canvas 有點相像。一般是 drawRect 的第一行代碼
    CGContextBeginPath(context); // setup context
    CGContextMoveToPoint(context, 75, 10);
    CGContextAddLineToPoint(context, 160, 150);
    CGContextAddLineToPoint(context, 10, 150);
    CGContextClosePath(context);
    [[UIColor greenColor] setFill]; // 設置 context 的填充顏色
    [[UIColor redColor] setStroke];
    CGContextDrawPath(context, kCGPathFillStroke); 
}
UIColor
UIColor *red = [UIColor redColor]; // class method, returnsautoreleased instance
UIColor *custom = [[UIColor alloc] initWithRed:(CGFloat)red // 0.0 to 1.0
                                          blue:(CGFloat)blue
                                         green:(CGFloat)green
                                         alpha:(CGFloat)alpha]; // 0.0 to 1.0 (opaque)
[redsetFill]; //fillcolorsetincurrentgraphicscontext(strokecolornotset)
[custom set]; // sets both stroke and fill color to custom (would override [red setFill])

UIView 有個 backgroundColor 屬性可以設置支持alpha通道的顏色。 不用透明度時確保@property BOOL opaqueNO 可以提高繪製效率

UIView @property CGFloat alpha 控制整個View的透明度

UIFont
UIFont *myFont = [UIFont systemFontOfSize:12.0];
UIFont *theFont = [UIFont fontWithName:@「Helvetica」 size:36.0];
NSArray *availableFonts = [UIFont familyNames];
NSString *text = ...;
[textdrawAtPoint:(CGPoint)pwithFont:theFont]; //NSStringinstancemethod How much space will a piece of text will take up when drawn?
CGSize textSize = [text sizeWithFont:myFont]; // NSString instance method?
UIImage
UIImage *image = [UIImage imageNamed:@「foo.jpg」];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:(NSString *)fullPath];
UIImage *image = [[UIImage alloc] initWithData:(NSData *)imageData];
[image drawAtPoint:(CGPoint)p]; // p is upper left corner of the image 
[image drawInRect:(CGRect)r]; // scales the image to fit in r 
[image drawAsPatternInRect:(CGRect)patRect; //tilestheimageintopatRect