使用 Core Graphics 向 UIImage 添加半透明层

Add a semi-transparent layer to UIImage using Core Graphics

我需要获取一个 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;
}

您忘记绘制要与当前上下文中的 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;

}

- (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;
}