代码之家  ›  专栏  ›  技术社区  ›  Duck

苹果手机。将PNG加载到CGLayer不起作用

  •  0
  • Duck  · 技术社区  · 14 年前

    我有一个CGLayer是这样创建的:

    CGSize size = CGSizeMake(500, 500);
    
    UIGraphicsBeginImageContext(tamanho);
    ctx = UIGraphicsGetCurrentContext();
    [self loadImageToCTX]; // this method loads an image into CTX
    
    lineLayer = CGLayerCreateWithContext (ctx, size, NULL);
    

    现在我有一个PNG,有alpha和一些内容。我需要把这个PNG加载到lineLayer,所以我。。。

    // lineLayer is empty, lets load a PNG into it
    CGRect superRect = CGRectMake(0,0, 500, 500);
    
    CGContextRef lineContext = CGLayerGetContext (lineLayer);
    CGContextSaveGState(lineContext);
    
    // inverting Y, so image will not be loaded flipped 
    CGContextTranslateCTM(lineContext, 0, -500);
    CGContextScaleCTM(lineContext, 1.0, -1.0);
    
    //  CGContextClearRect(lineContext, superRect);
    
    UIImage *loaded = [self recuperarImage:@"LineLayer.png"];
    CGContextDrawImage(lineContext, superRect, loaded.CGImage);
    CGContextRestoreGState(lineContext);
    

    如果我现在渲染ctx+lineLayer的内容,最终的图像只包含ctx。。。

    // if I render the contents to a view using the lines below, I see just CTX, lineLayer contents are not there
    // remember CTX has an image and lineLayer has a transparent loaded PNG
    // but when I render this, the final image contains just CTX's contents...
    // this is how it is rendered.
    
    CGContextDrawLayerInRect(ctx, superRect, lineLayer);
    myView.image = UIGraphicsGetImageFromCurrentImageContext();
    

    2 回复  |  直到 14 年前
        1
  •  1
  •   tc.    14 年前

    我不太清楚这条线在做什么:

    lineLayer = CGLayerCreateWithContext (ctx, size, NULL);
    

    你为什么要重复使用 ctx ? 我的理解是,这意味着lineContext==ctx,因此对CGContextDrawLayerInRect()的调用会将上下文的内容拉入自身,这不是很好(可能处理不好)。

    还需要检查“loaded”是否为非nil。

    而且,要画一个图像要做很多工作。做点像这样的事

    UIGraphicsBeginImageContext(tamanho);
    ctx = UIGraphicsGetCurrentContext();
    [self loadImageToCTX];
    [[UIImage imageNamed:@"LineLayer.png"] drawInRect:(CGRect){{0,0},{500,0}}];
    myView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
        2
  •  0
  •   Duck    14 年前

    我发现了问题所在。 台词

    CGContextTranslateCTM(lineContext, 0, -500);
    CGContextScaleCTM(lineContext, 1.0, -1.0);
    

    谢谢你们!