【问题标题】:Add a semi-transparent layer to UIImage using Core Graphics使用 Core Graphics 向 UIImage 添加半透明层
【发布时间】:2023-04-03 10:00:02
【问题描述】:

我需要获取一个 UIImage 并添加一个半透明层以生成一个新的 UIImage。我想我已经接近了,但还是有问题。这是我的代码:

- (UIImage*) addLayerTo:(UIImage*)source
{
    CGSize size = [source size];
    UIGraphicsBeginImageContext(size);
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:0.18];

    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetRGBStrokeColor(context, 0.2, 0.5, 0.1, 0.18);
    CGContextFillRect(context, rect);
    UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return testImg;
}

【问题讨论】:

  • 怎么了?你看到了什么你不希望看到的?你想看什么?

标签: ios objective-c uiimage core-graphics alpha


【解决方案1】:
- (UIImage*) addLayerTo:(UIImage*)source
{
    CGSize size = [source size];
    // create context with UIScrean scale
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    // get new context
    CGContextRef ctx1 = UIGraphicsGetCurrentContext();
    // draw view
    CGContextDrawImage(ctx1, CGRectMake(0.0f, 0.0f, size.width, size.height), source.CGImage);
    // set fill color
    UIColor *fillColor = [UIColor purpleColor];
    // fill with it
    CGContextSetFillColorWithColor(ctx1, fillColor.CGColor);
    CGContextFillRect(ctx1, CGRectMake(0, 0, size.width, size.height));

    // create new image
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    // end context
    UIGraphicsEndImageContext();

    return outputImage;
}

【讨论】:

    【解决方案2】:

    您忘记在当前上下文中绘制要与source 图像混合的当前图像。

    - (UIImage*) addLayerTo:(UIImage*)source
    {
      CGSize size = [source size];
      UIGraphicsBeginImageContext(size, NO, [UIScreen mainScreen].scale); // Use this image context initialiser instead
    
      CGRect rect = CGRectMake(0, 0, size.width, size.height);
      [self drawInRect: rect] // Draw the current image in context
      [source drawInRect:rect blendMode:kCGBlendModeNormal alpha:0.18]; // Blend with other image
    
      CGContextRef context = UIGraphicsGetCurrentContext();
      CGContextSetRGBStrokeColor(context, 0.2, 0.5, 0.1, 0.18);
      CGContextFillRect(context, rect);
      UIImage *testImg =  UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      return testImg;
    

    }

    【讨论】:

      猜你喜欢
      • 2012-03-15
      • 2013-03-26
      • 1970-01-01
      • 2013-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多