archeopetrix
archeopetrix

Reputation: 171

Core Graphics - Is there a way to get/retrieve the currently set CGColor from CGContext?

We can set a CGColor as fill or stroke colour for a given context by doing something like:

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

But how can we get or retrieve currently set fill or stroke colour from a given context?

So is there an API something like:

CGColorRef CGContextGetFillColorFromContext(CGContextRef c)

which takes a CGContext as input parameter and returns it's currently set Fill or stroke CGColour? If not this then is there some other indirect way to achieve this?

I am hoping for the above because the color is set in one class and it is needed back in some other class like so:

In 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]; 
}

In NSString+MyCategory.m

-(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}];
}

Upvotes: 1

Views: 458

Answers (1)

matt
matt

Reputation: 535999

So is there an API something like

No, there is not, because there doesn't need to be.

But how can we get or retrieve currently set fill or stroke colour from a given context?

The simple answer is that you cannot possibly not know what the currently set color is, because you yourself were the one who set it, as in the line you yourself cite:

CGContextSetFillColorWithColor(ctx, color.CGColor);

If you know you're going to need that color somewhere else, record it in a variable (e.g. an instance variable if the info needs to be available from another method at another time). Plan ahead for your own future needs; that is what programming is.

Upvotes: 2

Related Questions