2

我需要捕获帧缓冲区并将其保存到文件中,
我正在使用抓取示例代码的儿子来捕获缓冲区,但它没有给我鼠标指针,

所以我自己绘制鼠标指针,请参考下面的代码片段,一切正常,除了光标没有绘制在正确的位置,x & y 坐标略有偏差,形成 Cocoa 框架,我得到鼠标指针位置,似乎我应该以某种方式获得鼠标光标边界,所以我可以使用相同的矩形来绘制光标,
任何想法,如何使用 Mousse 位置指针在正确的位置绘制鼠标图像?

-(CGImageRef)appendMouseCursor:(CGImageRef)pSourceImage{
    // get the cursor image 
    NSPoint mouseLoc; 
    mouseLoc = [NSEvent mouseLocation]; //get cur

    NSLog(@"Mouse location is x=%d,y=%d",(int)mouseLoc.x,(int)mouseLoc.y);

    // get the mouse image 
    NSImage *overlay    =   [[[NSCursor arrowCursor] image] copy];

    NSLog(@"Mouse location is x=%d,y=%d cursor width = %d, cursor height = %d",(int)mouseLoc.x,(int)mouseLoc.y,(int)[overlay size].width,(int)[overlay size].height);

    int x = (int)mouseLoc.x;
    int y = (int)mouseLoc.y;
    int w = (int)[overlay size].width;
    int h = (int)[overlay size].height;
    int org_x = x-w/2;
    int org_y = y-h/2;

    size_t height = CGImageGetHeight(pSourceImage);
    size_t width =  CGImageGetWidth(pSourceImage);
    int bytesPerRow = CGImageGetBytesPerRow(pSourceImage);

    unsigned int * imgData = (unsigned int*)malloc(height*bytesPerRow);

    // have the graphics context now, 
    CGRect bgBoundingBox = CGRectMake (0, 0, width,height);

    CGContextRef context =  CGBitmapContextCreate(imgData, width, 
                                                  height, 
                                                  8, // 8 bits per component 
                                                  bytesPerRow, 
                                                  CGImageGetColorSpace(pSourceImage), 
                                                  CGImageGetBitmapInfo(pSourceImage));

    // first draw the image 
    CGContextDrawImage(context,bgBoundingBox,pSourceImage);

    // then mouse cursor 
    CGContextDrawImage(context,CGRectMake(0, 0, width,height),pSourceImage);

    // then mouse cursor 
    CGContextDrawImage(context,CGRectMake(org_x, org_y, w,h),[overlay CGImageForProposedRect: NULL context: NULL hints: NULL] );


    // assuming both the image has been drawn then create an Image Ref for that 

    CGImageRef pFinalImage = CGBitmapContextCreateImage(context);

    CGContextRelease(context);

    return pFinalImage; /* to be released by the caller */
}  

一切正常,除了鼠标位置略有偏差,从

4

1 回答 1

7

您需要考虑鼠标光标的热点,即光标中的像素,即“活动点”。您可以从返回相对于光标坐标系左下角的-hotspot方法中获取此信息。NSCursorNSPoint

所以你的代码可能应该是这样的:

NSPoint offset = [[NSCursor arrowCursor] hotSpot];

int org_x = (x - w/2) - offset.x;
int org_y = (y - h/2) - offset.y;
于 2011-11-11T03:48:53.483 回答