2010-07-31 98 views
0

我想在drawRect中保留以前的繪圖(系統每次清除它),而且似乎要使用位圖上下文並且足夠肯定,這個作品除了現在我的顏色消失以外,只剩下黑色和白色。我的顏色位圖在drawRect(iPhone)中只有黑色和白色

這裏是我的 「靜態」 的背景下

-(id)initWithCoder:(NSCoder *)aDecoder { 
... 
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
contextRef = CGBitmapContextCreate(NULL, 
      320, 
      640, 
      8, 
      320*4, 
      colorSpace, 
      kCGImageAlphaPremultipliedLast); 
... 
} 

,這裏是我的更換背景:

-(void)drawRect:(CGRect)rect { 
     myDrawRoutine(); 

CGContextRef context = UIGraphicsGetCurrentContext(); 

CGContextDrawImage(context, rect, CGBitmapContextCreateImage(contextRef)); 

} 

這是平局常規的膽量:

... 
// CGContextRef context = UIGraphicsGetCurrentContext(); 
CGContextRef context = contextRef; 
if(!(context)) 
    return; 

CGContextSetFillColor(context, CGColorGetComponents([co CGColor])); 
CGContextSetStrokeColor(context, CGColorGetComponents([co CGColor])); 

CGContextFillEllipseInRect(context, CGRectMake((*i)->x, 
       (*i)->y, 
       (*i)->diam, 
       (*i)->diam)); 
... 
} 
+0

對於這種設置,CGLayer比CGBitmapContext更適合於緩存你的darwings。 – tonklon 2010-07-31 10:30:03

回答

0

了!感謝這個線程 Extracting rgb from UIColor

我得到了答案 - 使用CGContextSetRGBFillColor代替,然後用CGColorGetComponents的RGB間接饋入它。

CGColorRef color = [co CGColor];  
int numComponents = CGColorGetNumberOfComponents(color); 
CGFloat red; 
CGFloat green; 
CGFloat blue; 
CGFloat alpha; 
if (numComponents == 4) 
{ 
    const CGFloat *components = CGColorGetComponents(color); 
    red = components[0]; 
    green = components[1]; 
    blue = components[2]; 
    alpha = components[3]; 
} 

// CGContextSetFillColor(context, CGColorGetComponents([co CGColor])); 
// CGContextSetStrokeColor(context, CGColorGetComponents([co CGColor])); 
CGContextSetRGBFillColor(context, red, green, blue, alpha); 
CGContextSetRGBStrokeColor(context, red, green, blue, alpha); 

CGContextFillEllipseInRect(context, CGRectMake((*i)->x, 
               (*i)->y, 
               (*i)->diam, 
               (*i)->diam)); 
} 
0

感謝tonclon

這取得了:)速度增加

的地獄,但它仍然在吸引黑白:(

這裏是上面的代碼+修改...

這裏是我的「靜態上下文「:

-(id)initWithCoder:(NSCoder *)aDecoder { 
    ... 
    } 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    contextRef = CGBitmapContextCreate(NULL, 
        320, 
        640, 
        8, 
        320*4, 
        colorSpace, 
        kCGImageAlphaPremultipliedLast); 
    CGColorSpaceRelease(colorSpace); 

    cglayer = CGLayerCreateWithContext(contextRef, CGSizeMake(320.0f, 640.0f), NULL); 
    contextRef = CGLayerGetContext(cglayer); 
    ... 
    } 

,這裏是我的‘即cglayer來代替更換背景’(上下文不再更換)。

-(void)drawRect:(CGRect)rect { 
    for(std::vector<Body*>::iterator i = bodyVec.begin(); i < bodyVec.end(); ++i) 
     move(i); 

    CGContextRef context = UIGraphicsGetCurrentContext(); 

// CGContextDrawImage(context, rect, CGBitmapContextCreateImage(contextRef)); 
    CGContextDrawLayerInRect(context, rect, cglayer); 

} 

( 「繪製常規的膽量」 保持不變。)

相關問題