【问题标题】:UIColor with pattern image and color behind带有图案图像和颜色的 UIColor
【发布时间】:2013-11-17 09:03:11
【问题描述】:

我正在尝试设置一些UIView 元素的背景颜色。

我想用蓝色和顶部的破折号来绘制它。 我知道我可以制作一个新的 UIView 作为它的孩子并用

[UIColor colorWithPatternImage:pattern]

但我特别想要一个UIView,所以要一个UIColor,上面有蓝色背景和图案图像。

马尔科

编辑:

图案图片如下:

结果应该是:

【问题讨论】:

  • 你必须继承 UIView 并为此重写 drawRect 方法
  • 我想避免的。我有一些对象(购买)的库,但我无法访问视图层次结构。我只能我们.backgroundColor

标签: ios uiview background-color uicolor


【解决方案1】:
- (UIImage *)image:(UIImage *)image withColor:(UIColor *)color {
    CGSize backgroundSize = image.size;
    UIGraphicsBeginImageContext(backgroundSize);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGRect backgroundRect;
    backgroundRect.size = backgroundSize;
    backgroundRect.origin.x = 0;
    backgroundRect.origin.y = 0;
    float r,g,b,a;
    [color getRed:&r green:&g blue:&b alpha:&a];
    CGContextSetRGBFillColor(ctx, r, g, b, a);
    CGContextFillRect(ctx, backgroundRect);

    CGRect imageRect;
    imageRect.size = image.size;
    imageRect.origin.x = (backgroundSize.width - image.size.width)/2;
    imageRect.origin.y = (backgroundSize.height - image.size.height)/2;

    // Unflip the image
    CGContextTranslateCTM(ctx, 0, backgroundSize.height);
    CGContextScaleCTM(ctx, 1.0, -1.0);

    CGContextSetBlendMode(ctx, kCGBlendModeMultiply);
    CGContextDrawImage(ctx, imageRect, image.CGImage);

    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return newImage;
}

使用上述方法如下

 UIImage *img = [UIImage imageNamed:@"Z2AmQ.png"];
 [self.tmpView setBackgroundColor:[UIColor colorWithPatternImage:[self image:img withColor:[UIColor blueColor]]]];

【讨论】:

  • 哇,这很好用。出于好奇,对于所有其他项目,用您的代码执行此操作或使用模式在顶部创建新的 UIView 更有效的方法是什么? :D
  • 这取决于它只是为了设计目的,然后我认为添加 2 个视图是不必要的。但我不知道在性能方面哪种方法最好:)
  • 此代码仅适用于 iphone 4s 和 5 模拟器。此外,还有一些关于 CGContextSaveGState、CGContextSetBlendMode 等的警告,说:Invalid context 0x0...严重错误...导致整体退化...即将更新的致命错误。你有什么解决方法吗? @PratyushaTerli
猜你喜欢
  • 1970-01-01
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多