如何在UIImageView上层叠部分透明的UIImageView?

时间:2013-07-18 09:12:17

标签: ios uiimageview

我有一个带有固定图像的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];

1 个答案:

答案 0 :(得分:2)

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

此外:

  • 您无需在绘制前清除上下文,因为它已被清除。

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