在代码中动态更改详细信息显示按钮的颜色

时间:2013-05-22 16:12:47

标签: ios colors indicator detail disclosure

我之前已经问过类似的问题,但大多数答案都说创建一个具有所需颜色的新细节披露按钮图像(例如How to change color of detail disclosure button for table cell)。

我希望能够在运行时动态地将其更改为我选择的任何颜色,因此使用预先配置的图像是不可行的。

从阅读中,我认为可能有几种方法可以做到这一点,但我不确定哪种方法最好,或者确切地知道如何做到这一点:

  1. 在代码中绘制所需的色环,并在圆圈和箭头右侧覆盖阴影圆形图像(使用清晰的Alpha通道进行休息,因此绘制的色圈仍然可见)

  2. 在UIImageView中添加阴影圆形图像,并用作遮罩,在此阴影圆圈内填充填充,然后覆盖箭头。

  3. 添加灰度图像,自行遮盖,覆盖所需颜色(例如http://coffeeshopped.com/2010/09/iphone-how-to-dynamically-color-a-uiimage),然后用箭头图像覆盖。

  4. 最好的方法是什么,有没有人有任何代码显示如何做到这一点?

2 个答案:

答案 0 :(得分:2)

我使用以下辅助方法为灰度图像着色。它采用灰度图像,色调颜色和用于确保色调仅出现在灰度图像的一部分中的选项蒙版图像。此方法还可确保新图像与原始图像具有相同(如果有)可调整大小的插图。

+ (UIImage *)tintImage:(UIImage *)baseImage withColor:(UIColor *)color mask:(UIImage *)maskImage {
    UIGraphicsBeginImageContextWithOptions(baseImage.size, NO, baseImage.scale);

    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect area = CGRectMake(0, 0, baseImage.size.width, baseImage.size.height);

    CGContextScaleCTM(ctx, 1, -1);
    CGContextTranslateCTM(ctx, 0, -area.size.height);

    CGContextSaveGState(ctx);
    if (maskImage) {
        CGContextClipToMask(ctx, area, maskImage.CGImage);
    } else {
        CGContextClipToMask(ctx, area, baseImage.CGImage);
    }

    [color set];
    CGContextFillRect(ctx, area);
    CGContextRestoreGState(ctx);

    CGContextSetBlendMode(ctx, kCGBlendModeOverlay);

    CGContextDrawImage(ctx, area, baseImage.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    if (!UIEdgeInsetsEqualToEdgeInsets(baseImage.capInsets, UIEdgeInsetsZero)) {
        newImage = [newImage resizableImageWithCapInsets:baseImage.capInsets];
    }

    return newImage;
}

这是非视网膜灰度细节披露图像: enter image description here

这是视网膜版本: enter image description here

这是非视网膜面罩(在引号之间 - 它主要是白色): “enter image description here

视网膜面膜(引号之间: “enter image description here

答案 1 :(得分:0)

还要考虑在标签中使用图标字体而不是图像。像glyphicons这样的东西。然后,您可以将文本颜色设置为您想要的任何颜色。您还有很好的缩放选项。成本是你在某些情况下没有那么精确的控制,但它应该适合你的情况。