累積的一些零散筆記,整理成六個主題,都是日常開發會反覆用到的小片段。
把 view 的 layer 渲染進當前的圖形上下文,就能得到一張圖片:
#import <QuartzCore/QuartzCore.h> UIGraphicsBeginImageContext(self.view.bounds.size); [self.view.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); // 存到相簿 UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
若要指定尺寸,把 CGSize 傳給 UIGraphicsBeginImageContext 即可;輸出的位元資料可用 UIImagePNGRepresentation 或 UIImageJPEGRepresentation 取得。
顏色與字型由 UIColor 與 UIFont 負責:
UIColor *redColor = [UIColor redColor]; [redColor set]; // 設定為後續繪圖的顏色 UIFont *font = [UIFont systemFontOfSize:14.0]; // 系統字型 [myLabel setFont:font];
drawRect: 與 setNeedsDisplay:自訂繪圖要重寫 drawRect:,並在資料變動時呼叫 setNeedsDisplay 請系統重畫。
Core Graphics 流程:UIKit 提供的 UIRectFill、UIRectFrame 只能處理簡單矩形,複雜圖形得走 Core Graphics:
iPhone 上只有一個 window,對應多個 view,而這些 view 的邏輯關係全靠控制器來組織。大致結構是:window 裡放主控制器(例如 navigation controller),主控制器底下掛各個 view controller,每個 view controller 相當於一個根視圖並可以再裝其他視圖;而 view 由程式碼檔(.h/.m)與介面檔(.xib)組成,兩者必須正確關聯。
上下翻頁的動畫系統已經封裝好了:
[UIView beginAnimations:@"Curl" context:nil];
[UIView setAnimationDuration:1.25];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp
forView:self.view cache:YES];
[UIView commitAnimations];
CurlUp 是向上翻,CurlDown 則是向下翻。
UIImageView 預設 userInteractionEnabled 為 NO,必須先打開:
UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
imgView.userInteractionEnabled = YES;
UITapGestureRecognizer *singleTap =
[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickImage)];
[imgView addGestureRecognizer:singleTap];
[singleTap release];
做一張全屏歡迎圖命名為 Default.png 放進專案資源即可。若希望它停留久一點再進入主畫面,可以在啟動方法中插入延遲:
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[NSThread sleepForTimeInterval:5.0];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
return YES;
}
不過要提醒:在啟動階段 sleep 會讓 App 看起來像是當機,Apple 審核也可能有意見。真要延長品牌曝光,比較穩妥的做法是自己在主畫面之上做一個動畫式開場。