如何在视图的图层颜色发生变化时使不同的颜色外观

时间:2014-05-23 06:37:10

标签: ios iphone uiview calayer cgcontext

我正在做一些自定义下载进度栏(子类)UIButton(或)我也可以在UIView中做,每件事情都很好,现在我想改变颜色标题作为收益的进展,例如你可以在下面的图像中看到显示我现在正在获得的,

enter image description here

我想要的就像下面的图像

enter image description here

我希望在下载过程中将标题的颜色更改为白色或其他颜色,我有什么方法可以做,任何示例代码。

我通过使用以下代码实现这一目标

 - (void)drawInContext:(CGContextRef)progressContext
  {

     CGContextSetFillColorWithColor(progressContext, self.progressLayerColor.CGColor);
     CGMutablePathRef Path = CGPathCreateMutable();
     CGRect boundsRect = self.bounds;
     CGPathMoveToPoint(Path, NULL, boundsRect.origin.x, boundsRect.origin.y);

     CGPathAddRect(Path, NULL, CGRectMake(0, 0, self.progress, 35));
     CGPathCloseSubpath(Path);
     CGContextAddPath(progressContext, Path);
     CGContextFillPath(progressContext);
     CGContextSetBlendMode(progressContext, kCGBlendModeClear);
     CGContextFillPath(progressContext);

     CGPathRelease(Path);

  }

3 个答案:

答案 0 :(得分:2)

我用两个UILabel做到这一点,一个带有绿色背景和白色文本,一个带有白色背景和黑色文本,绿色一个带有另一个带有相同的框架。

最顶层的标签有一个CAShapeLayer,因为它的层mask。 CAShapeLayer从左到右在整个长度上具有单个宽(至少标签的高度)黑色笔划。

默认情况下,这会使整个视图显示为绿色。到目前为止,没用。

但是,CAShapeLayer具有(可动画的)strokeEnd属性。如果将此值设置为0.0,则绿色标签将不可见。设置为0.5,你看到一半和一半。

现在,您可以通过更新此遮罩层的strokeEnd属性来设置进度表的动画方法。

答案 1 :(得分:2)

借助@jrturton的建议,我能够制作这种进度条,


CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = _labelGreen.bounds;//it the label on top with green background and white text color
CGMutablePathRef mutPath = CGPathCreateMutable();
CGPathMoveToPoint(mutPath, NULL, 0, 0);
CGPathAddRect(mutPath, NULL, CGRectMake( 0, 0, progress, _labelGreen.frame.size.height)); //as the progress cganges the width of mask layer also changes
maskLayer.path = mutPath;//set the path

_labelGreen.layer.mask = maskLayer;


结果输出将如下图所示 enter image description here

答案 2 :(得分:1)

一个简单的解决方案是使用2 UIImageViews。下面的图像将具有白色背景和黑色文本的图像,上面的图像将具有带有白色文本的绿色背景。下面的图像将始终具有相同的帧,但另一个将以宽度0开始。随着下载的进行,您将增加它的宽度,它将开始覆盖下面的图像(使用黑色字体) 。当然,您可以使用“查看模式”:在展开的图像视图左侧,始终将图像放在左侧而不调整大小。

相关问题