Draw Text on a CVPixelBufferRef

The following code from apple (out of QTPixelBufferVCToCGImage) draws text to a CVPixelBufferRef with the name forgroundMask:

unsigned char*				      baseAddress;
unsigned int					rowbytes;
unsigned int					bytesPerRow;
CGColorSpaceRef colorSpace = NULL;

// lock the base address so we can paint on it, don't forget to release it in the end... .
CVPixelBufferLockBaseAddress(foregroundMask,0);
// get the base address of the pixel buffer (typecast into unsigned char for niceness).
baseAddress = (unsigned char*)CVPixelBufferGetBaseAddress(foregroundMask);
bytesPerRow = CVPixelBufferGetBytesPerRow(foregroundMask);

// how many bytes per row do we have ?
rowbytes = CVPixelBufferGetBytesPerRow(foregroundMask);
colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);

// Draw some text on the image just for something to do
DrawOnImage(baseAddress, bytesPerRow, maskWidth, maskHeight, colorSpace);

CVPixelBufferUnlockBaseAddress(foregroundMask,0);

Where you have a function

static OSStatus DrawOnImage(void *inBaseAddress, size_t inRowBytes, size_t inWidth, size_t inHeight, CGColorSpaceRef inColorSpace)
{
    CGContextRef theBitmapContext = NULL;

    if (NULL == inBaseAddress || 0 == inRowBytes || 0 == inWidth || 0 == inHeight || NULL == inColorSpace) return paramErr;

	theBitmapContext = CGBitmapContextCreate(inBaseAddress, inWidth, inHeight, 8, inRowBytes, inColorSpace, kCGImageAlphaPremultipliedFirst);
    if (NULL == theBitmapContext) return kCGErrorFailure;

    // what we want to draw
    const char *string = {"Hello World"};

    // some set up
    CGContextSelectFont(theBitmapContext, "Arial-Black", 32, kCGEncodingMacRoman);
    CGContextSetLineWidth(theBitmapContext, 1.5);
    CGContextSetRGBStrokeColor(theBitmapContext, 0.0, 0.0, 0.0, 1.0); // black
    CGContextSetRGBFillColor(theBitmapContext, 0.0, 1.0, 0.0, 1.0);   // bright green
  	CGContextSetTextPosition(theBitmapContext, 10, 10);
  	CGContextSetTextDrawingMode(theBitmapContext, kCGTextFillStroke);

    // draw it
    CGContextShowText(theBitmapContext, string, strlen( string ));

	if (NULL != theBitmapContext) CGContextRelease(theBitmapContext);

	return noErr;
}

Leave a Reply

You must be logged in to post a comment.