【问题标题】:How to layer a partially tranparent UIImageView on top of an UIImageView?如何在 UIImageView 之上分层部分透明的 UIImageView?
【发布时间】:2013-07-18 17:39:19
【问题描述】:

我有一个带有固定图像的 UIImageView。我想在顶部添加第二个 UIImageView,我打算旋转。我需要在运行时创建顶部图像。我找不到处理透明度的地方。它是在 UIImage 中还是在 UIImageView 中?到目前为止,我在 UIImageView 顶部有一个黑色背景,但我想看穿这些黑色像素。这是代码:(这是基于 Erica Sadun 的 Core iOS 6 Developers Cookbook )。我想在轮子上添加点来为控件的旋转添加一些反馈。

    float width=200, height=200;

    UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), YES, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    UIGraphicsPushContext(context);
    CGContextAddRect(context, CGRectMake(0, 0, width, height));
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
    CGContextFillPath(context);

    float lineWidth=4;
    CGContextAddEllipseInRect(context,  CGRectInset(CGRectMake(0, 0, width, height), lineWidth, lineWidth));
    CGContextSetLineWidth(context, 4);
    CGContextSetStrokeColorWithColor(context, [[UIColor redColor] CGColor]);
    CGContextStrokePath(context);
    UIGraphicsPopContext();

    dots = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    UIImageView * ivDots = [[UIImageView alloc] initWithImage:dots];
    UIImageView *iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"wheel.png"]];

    [self addSubview:iv];
    [self addSubview:ivDots];

【问题讨论】:

  • 顶部图像视图中使用的图像是否透明?即它在某处有透明度吗?
  • 我在运行时创建它,并且我希望它具有透明背景,因为我正在使用 [UIColor clearColor] 填充与 UIImage 相同大小的矩形。请参阅代码中的第 7 行。

标签: ios uiimageview


【解决方案1】:

您必须在 UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 0.0); 中使用 NO 指定不透明,否则生成的图像中将没有 alpha 通道 => 它将具有黑色像素而不是透明像素。

还有:

  • 你不需要在绘制之前清除上下文,因为它已经被清除了。

  • 您不需要推送和弹出上下文,因为您不会嵌套不同的上下文。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多