2016-12-26 231 views
0

我們可以做這樣的事情設置CGColor作爲填充或描邊顏色給定上下文:核心圖形 - 有沒有辦法從CGContext獲取/檢索當前設置的CGColor?

UIColor *color = [UIColor whiteColor]; 
CGContextRef ctx = UIGraphicsGetCurrentContext(); 
CGContextSetFillColorWithColor(ctx, color.CGColor); 

但如何我們可以得到或檢索當前設置從一個給定的上下文填充或描邊顏色?

那麼,有沒有一個API類似:

CGColorRef CGContextGetFillColorFromContext(CGContextRef c) 

這需要一個CGContext上作爲輸入參數,並返回它的當前設置填充或中風CGColour?如果不是這樣,那麼還有其他一些間接的方法來實現這一目標嗎

在MyView.m

- (void)drawRect:(CGRect)rect { 
    [[UIColor whiteColor] set] 
    //[@「Hello」 drawInRect:rect withFont:titleFont lineBreakMode:UILineBreakModeCharacterWrap alignment:UITextAlignmentLeft]; //draws text in the rect with white font colour but removed becasue of API deprecation 
    [@「Hello」 my_drawInRect:rect withFont:titleFont lineBreakMode:NSLineBreakByCharWrapping alignment:NSTextAlignmentLeft]; 
} 

在的NSString + MyCategory:

,因爲顏色是一個類集,它是需要背在其它的類一樣,所以我希望以上。米

-(void)my_drawInRect:(CGRect)rect withFont:(UIFont *)font lineBreakMode:(NSLineBreakMode)lineBreakMode alignment:(NSTextAlignment)alignment { 
    NSMutableParagraphStyle* paragraphStyle = [NSMutableParagraphStyle new]; 
    paragraphStyle.lineBreakMode = lineBreakMode; 
    paragraphStyle.alignment = alignment; 
    UIColor* color = nil; //Hoping to get it from UIGraphicsGetCurrentContext(); 
    [self drawInRect:rect withAttributes:@{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle, NSForegroundColorAttributeName:color}]; 
} 

回答

1

那麼,有沒有一個API類似

不,沒有,因爲沒有必要。

但是,我們如何從給定的上下文中獲取或檢索當前設置的填充或描邊顏色?

簡單的答案是,你不可能知道當前設置的顏色是什麼,因爲你自己是誰設置,如行了一個你自己舉:

CGContextSetFillColorWithColor(ctx, color.CGColor); 

如果您知道您將在其他地方需要該顏色,請將其記錄在變量中(例如,如果需要在另一時間從其他方法獲取信息,則使用實例變量)。爲未來的需求提前計劃;那編程

+0

感謝您的回覆。將它記錄在變量中是我計劃使用的明顯解決方案之一,以防無法直接從CGContext獲取它。我已經更新了我的問題,以提供更多的背景知道爲什麼我希望獲得這樣的API。 – archeopetrix

+0

但是,當你確認沒有直接的方式從當前的CGContext中獲取它時,我可以: (i)在NSString類別中修改上述方法以接受一個或多個參數(要使用的顏色)或 (ii)將顏色存儲/記錄在某個單例的屬性中,並在類別方法中從那裏訪問它。 如果我錯了,請糾正我 再次感謝您的幫助。很多你在這裏的答案在過去都非常有幫助。 – archeopetrix

相關問題