【问题标题】:Core Graphics - Is there a way to get/retrieve the currently set CGColor from CGContext?核心图形 - 有没有办法从 CGContext 获取/检索当前设置的 CGColor?
【发布时间】:2017-05-10 23:57:07
【问题描述】:

我们可以通过执行以下操作将 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.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}];
}

【问题讨论】:

    标签: ios objective-c macos core-graphics


    【解决方案1】:

    那么有没有类似的 API

    不,没有,因为不需要。

    但是我们如何从给定的上下文中获取或检索当前设置的填充或描边颜色?

    简单的答案是你不可能知道当前设置的颜色是什么,因为你自己是设置它的人,正如你自己引用的那行:

    CGContextSetFillColorWithColor(ctx, color.CGColor);
    

    如果您知道您将在其他地方需要该颜色,请将其记录在一个变量中(例如,如果信息需要在其他时间从另一个方法中获得,则将其记录在一个实例变量中)。为自己的未来需求提前计划;这就是编程

    【讨论】:

    • 感谢您的回复。将其记录在变量中是我计划使用的明显解决方案之一,以防无法直接从 CGContext 获取它。我已经更新了我的问题,以提供更多背景信息来说明我为什么希望使用这样的 API。
    • 但是正如您所确认的,没有直接的方法可以从当前的 CGContext 中获取它,所以我可以:(i)修改 NSString 类别中的上述方法以接受更多参数(用于使用的颜色) 或 (ii) 在某个单例的属性中存储/记录颜色,并在类别方法中从那里访问它。如果我错了,请纠正我再次感谢您的帮助。过去,您在 SO 上的很多答案都非常有帮助。
    • “需要”是避免在两个不同的地方管理单一颜色的状态。避免不必要的重复是基本的编程习惯。
    猜你喜欢
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多