【发布时间】:2015-08-16 12:47:43
【问题描述】:
我想在 NPAPI 插件 CGContextRef 中绘制文本,但我不知道如何让它工作。 我得到的 CGContext Ref 如下:
int16_t NPP_HandleEvent(NPP instance, void* event)
{
int16_t iRet = 0;
PluginObject *obj = (PluginObject *)instance->pdata;
NPCocoaEvent *cocoaEvent = (NPCocoaEvent *)event;
switch(cocoaEvent->type)
{
case NPCocoaEventDrawRect:
obj->m_NPContext = CGContextRetain(cocoaEvent->data.draw.context);
DrawSealOnContext(obj->m_NPContext, obj->m_pstSealAPInfo);
iRet = 1;
break;
default:
iRet = 0;
break;
}
return iRet;
}
在函数 DrawSealOnContext 中,我想在窗口中绘制一个椭圆和一些文本。函数如下:
int DrawSealOnContext(CGContextRef contextRef, PSEAL_APPEARANCE_INFO pstSealAPInfo)
{
// draw ellipses
CGRect rect = {2, 25, 146, 100};
CGContextSetLineWidth(contextRef, 4.0);
CGContextSetStrokeColorWithColor(contextRef, [NSColor blueColor].CGColor);
CGContextBeginPath(contextRef);
CGContextAddEllipseInRect(contextRef, rect);
CGContextDrawPath(contextRef, kCGPathStroke);
// draw text
CGContextSetFillColorWithColor(contextRef, [NSColor blueColor].CGColor);
NSMutableParagraphStyle * paragraphStyle = [[[NSParagraphStyle defaultParagraphStyle] mutableCopy] autorelease];
[paragraphStyle setAlignment:NSCenterTextAlignment];
NSDictionary * attributes = [NSDictionary dictionaryWithObject:paragraphStyle
forKey:NSParagraphStyleAttributeName];
NSString * mystr = @“hello\n and";
NSRect strFrame = { { 0, 0 }, { 150, 150 } };
[mystr drawInRect:strFrame withAttributes:attributes];
}
我可以在屏幕上显示椭圆,但没有显示文字?
我也试试这个:
// draw text
CGContextShowText(contextRef, "hello", 5);
也不行。
我的程序出了什么问题,非常感谢你的 答案。
【问题讨论】:
-
虽然这不是您的代码的问题,但请注意您应该不存储上下文,因为您在第一个代码块中。在 CG+Cocoa 模型组合中,你给出的上下文只保证在 HandleEvent 调用期间是有效的,而且它可能会因调用而异。如果您在函数返回后的任何时间尝试使用您存储的上下文,则行为未定义。
-
那我如何在 CGContext 中绘制椭圆和文本?将所有代码放入函数中: int16_t NPP_HandleEvent(NPP instance, void* event) ?
-
我尝试将绘制文本代码放入函数:int16_t NPP_HandleEvent(NPP instance, void* event),它也不起作用。也许还有其他问题,或者我不能以这种方式直接在 CGContext 上绘制文本?我尝试使用另一个函数:CGContextShowTextAtPoint(contextRef, 8, 72, "hello", 6),它可以工作。但问题是,这个功能不能画汉字,不符合我的要求。
-
我需要使用函数:[mystr drawInRect:strFrame withAttributes:attributes];但我不知道如何在我的情况下使用它!
标签: plugins cgcontext drawtext