2012/4/10

UIView covert to UIImage

UIGraphicsBeginImageContext(self.frame.size);
[_contentView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

KVO,Key-Value Observing

KVO,Key-Value Observing
有一點類似NSNotification,但其實更像是binding

NSNotification類似Java的event流程,
但如果用NSNotification來實現binding,
就要寫setter、post、addObserver、跟對應的selector或block
若只為了監控幾個屬性的變化,就要寫好幾段程式其實挺累人的
弄不好還會提供類別間的隅和性

使用KVO可以容易的化解這個問題
example
[target addObserver:self 
    forKeyPath:@"clickCount" 
    options:NSKeyValueObservingOptionOld
    context:@selector(onEvent)];
target:欲監控的屬性的主人(sender)
addObserver:接收監控的實體(receiver)
options:(接受的值,改變前的值還是改變後的值)
context:要傳給observer的參數,這邊我們用selector,接放時則執行這個method


而observer要實作以下這個方法,來對監控事件的發生做應該處理
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
 NSLog(@"[MyObserver]observeValueForKeyPath");
 SEL method=(SEL)context;
 [self performSelector:method];
}
相對於NSNotification,要寫的程式就少了許多

注意:
只能有@property的屬性,

2012/4/3

Quartz 2D

Function 
Quartz2D的functio n太多,只至把用過的稍微記一下

  • CGContextRef CGContext,一個ObjectiveC製作繪圖的資料型態(參照)
  • CGLayerRef
  • UIGraphicsGetCurrentContext
  • (CGContextRef) CGBitmapContextCreate  產生bitmap形態的ContextRef
  • (CGGradientRef) CGGradientCreateWithColorComponents  產生一個漸層填色
  • CGContextDrawLinearGradient  套用一個漸層的繪圖填色
  • CGColorSpaceCreateDeviceGray  產生裝置支援的灰階色域(類似色票)
  • CGColorSpaceCreateDeviceRGB  產生裝置支援的RGB色域
  • CGBitmapContextCreateImage 將CGContextRef 轉成CGImageRef
  • CGContextClipToMask  對CGContextRef套用CGImageRef格式的mask
  • CGContextScaleCTM  延展座標
  • CGContextTranslateCTM  位移座標


位移原點作標


CGContextSaveGState 與 CGContextRestoreGState,花了一點時間將CGContextGSave與CGContextRestoreGState弄懂,CGContextRef是一個線性的繪圖資料型態,他儲存產生繪圖的所有需要資訊。
一般而言,可以從取得bitmap、layer、window、pdf等透過CoreGraphics或者UIKit的一些
function取得CGContextRef,如CGBitmapContextCreate、 UIGraphicsGetCurrentContext。取得CGContextRef之後,就可以對他進行繪圖,而所有的繪圖資料都是透過一些CG的function將context一層一層的覆蓋下去,所以我們可以想成每次的修改,都是針對目前的Status進行修改。因此,原本的圖形繪圖資料,經function處理後,產生新的status,舊的圖形資料就被蓋下去
由於是一層一層蓋下去的,每蓋一層,就是一個新的Status,如同油畫一樣,所以舊的資料就會被蓋到下層無法取得
因此有兩個function為CGContextSaveGState 與 CGContextRestoreGState

CGContextSaveGState,將目前的STATUS push一個copy到一個Stack,
之後的修改將不會動到此STATUS,有點類似紀錄點的意思

CGContextRestoreGState,從Stack pop一個Status回來,原先的status之後的修改將會被捨棄掉,可以這樣想:
A--->B--->save--->C--->D--->E--->F--->restore--->B

但並非所有修改都支援status的save,只有下表的CoreGraphic 參數支援status的save。
注意,下表提供的path,CGContextStrokePath、CGContextStrokeRect之類的動作,是不支援Status Save的,但先前的moveTo、lineTo、color才支援Status Save
https://developer.apple.com/library/ios/#documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview.html#//apple_ref/doc/uid/TP30001066-CH202-CJBIBHHB



Creating Affine Transforms



ref: