2010-10-15 61 views
3

我想繪製到位圖上下文但空來。我相信我正在創造一些東西,因爲我可以初始化上下文,繪製一些東西,然後從中創建一個圖像並繪製該圖像。我不能做的是,在初始化之後,觸發進一步繪製在其上繪製更多項目的上下文。我不確定我是否忽略了一些常見的做法,這意味着我只能在某些地方繪製它,或者我必須做其他事情。下面是我做的。繪製到位圖上下文

我複製了蘋果公司提供的輔助功能用一個修改,以獲得色彩空間,因爲它不是編譯(這是適用於iPad,不知道是否該事項):

CGContextRef MyCreateBitmapContext (int pixelsWide, int pixelsHigh) 
{ 
    CGContextRef context = NULL; 
    CGColorSpaceRef colorSpace; 
    void *   bitmapData; 
    int    bitmapByteCount; 
    int    bitmapBytesPerRow; 

    bitmapBytesPerRow = (pixelsWide * 4);// 1 
    bitmapByteCount  = (bitmapBytesPerRow * pixelsHigh); 


    colorSpace = CGColorSpaceCreateDeviceRGB(); //CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);// 2 

    bitmapData = malloc(bitmapByteCount);// 3 
    if (bitmapData == NULL) 
    { 
     fprintf (stderr, "Memory not allocated!"); 
     return NULL; 
    } 
    context = CGBitmapContextCreate (bitmapData,// 4 
            pixelsWide, 
            pixelsHigh, 
            8,  // bits per component 
            bitmapBytesPerRow, 
            colorSpace, 
            kCGImageAlphaPremultipliedLast); 
    if (context== NULL) 
    { 
     free (bitmapData);// 5 
     fprintf (stderr, "Context not created!"); 
     return NULL; 
    } 
    CGColorSpaceRelease(colorSpace);// 6 

    return context;// 7 
} 

我初始化它在下面幾樣我的init()方法繪製只是要確保它看起來是正確的:

mContext = MyCreateBitmapContext (rect.size.width, rect.size.height); 

    // sample fills 
    CGContextSetRGBFillColor (mContext, 1, 0, 0, 1); 
    CGContextFillRect (mContext, CGRectMake (0, 0, 200, 100)); 
    CGContextSetRGBFillColor (mContext, 0, 0, 1, .5); 
    CGContextFillRect (mContext, CGRectMake (0, 0, 100, 200)); 


    CGContextSetRGBStrokeColor(mContext, 1.0, 1.0, 1.0, 1.0); 
    CGContextSetRGBFillColor(mContext, 0.0, 0.0, 1.0, 1.0); 
    CGContextSetLineWidth(mContext, 5.0); 
    CGContextAddEllipseInRect(mContext, CGRectMake(0, 0, 60.0, 60.0)); 
    CGContextStrokePath(mContext); 

在我的drawRect方法,我創建一個圖像從它呈現它。也許我應該創建並保持這個圖像作爲一個成員變種,並更新它,每次我畫新的東西,而不是每幀創建圖像? (關於這方面的一些建議是很好的):

// draw bitmap context 
CGImageRef myImage = CGBitmapContextCreateImage (mContext); 
CGContextDrawImage(context, rect, myImage); 
CGImageRelease(myImage); 

然後作爲一個測試,我試着畫一個圓圈,當我觸摸到,但沒有任何反應,並且觸摸絕對是觸發:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    CGPoint location; 
    for (UITouch* touch in touches) 
    { 
     location = [touch locationInView: [touch view]]; 
    } 
    CGContextSetRGBStrokeColor(mContext, 1.0, 1.0, 1.0, 1.0); 
    CGContextSetRGBFillColor(mContext, 0.0, 0.0, 1.0, 1.0); 
    CGContextSetLineWidth(mContext, 2.0); 
    CGContextAddEllipseInRect(mContext, CGRectMake(location.x, location.y, 60.0, 60.0)); 
    CGContextStrokePath(mContext); 
} 

幫助?

回答

1

[自setNeedsDisplay]; !!!!

!!!!!!!!!

所以這是因爲drawRect中從來沒有被初始化後,所謂的,因爲它不知道它需要刷新。我的理解是,我應該只要在繪製時調用setNeedsDisplay並且這似乎工作。 :)

+0

您可以通過點擊綠色勾號「接受」您自己的答案... – 2015-06-08 13:11:11