2012-03-19 75 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