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

}

关于ios - 使用Core Graphics将半透明层添加到UIImage,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30916689/

10-15 15:28