2012-03-19 59 views
-5

我有此代码,其中应重复相同的UIImage:一个UIImage CoreGraphics在创建不重复

UIView *paperMiddle = [[UIView alloc] initWithFrame:CGRectMake(0, 34, 320, rect.size.height - 34)]; 
UIImage *paperPattern = paperBackgroundPattern(context); 
paperMiddle.backgroundColor = [UIColor colorWithPatternImage:paperPattern]; 
[self addSubview:paperMiddle]; 

而这正是paperBackgroundPattern方法:

UIImage *paperBackgroundPattern(CGContextRef context) { 
    CGRect paper3 = CGRectMake(10, -15, 300, 16); 
    CGRect paper2 = CGRectMake(13, -15, 294, 16); 
    CGRect paper1 = CGRectMake(16, -15, 288, 16); 

    //Shadow 
    CGContextSetShadowWithColor(context, CGSizeMake(0,0), 10, [[UIColor colorWithWhite:0 alpha:0.5]CGColor]); 
    CGPathRef path = createRoundedRectForRect(paper3, 0); 
    CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]); 
    CGContextAddPath(context, path); 
    CGContextFillPath(context); 

    //Layers of paper 
    CGContextSaveGState(context); 
    drawPaper(context, paper3); 
    drawPaper(context, paper2); 
    drawPaper(context, paper1); 

    CGContextRestoreGState(context); 
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(320, 1), NO, 0); 
    UIImage *paperImage = UIGraphicsGetImageFromCurrentImageContext(); 
    UIGraphicsEndImageContext(); 
    return paperImage; 
} 

它不重复图片。这里有图像的结果是它显示为屏幕的顶部像素(这不是我给出的框架)。

任何想法为什么?

+4

请不要删除并重新发布您的问题http://stackoverflow.com/questions/9767477/isnt-repeating-background-created-in-coregraphics。相反,编辑并改进它们。 – 2012-03-19 21:08:15

回答

2

我不知道context是通过了什么,但不管它是什么,你都不应该画它。而且你没有在你用UIGraphicsBeginImageContextWithOptions所做的上下文中绘制任何东西。

如果要生成图像,则不需要传递上下文,只需使用UIGraphicsBeginImageContextWithOptions为您生成的图像。

UIImage *paperBackgroundPattern() { 
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(320, 1), NO, 0); 
    CGContextRef context = UIGraphicsGetCurrentContext(); 

    // draw into context, then... 

    UIImage *paperImage = UIGraphicsGetImageFromCurrentImageContext(); 

    UIGraphicsEndImageContext(); 

    return paperImage; 
} 

此外 - 你真的想要制作一个320点宽,1高的图像?看起来很奇怪,你正在将这些精巧的东西绘制成这样一个小小的图像。

+0

完美,谢谢。图像有一个内部阴影,7.5像素大。所以它需要比这更大,以便它不会显示来自顶部或底部的阴影。我想我会删除,虽然因为我的代码正在改变为这种方法。 – Andrew 2012-03-19 21:47:37