CGContextSetLineDash不能与虚线一起使用

时间:2018-09-17 15:35:38

标签: macos core-graphics dotted-line

我正在使用Mac OS X SDK 10.12在Mac上使用CGContextSetLineDash绘制一个像素虚线。下面的代码在位图上下文上画一条线,然后将位图保存到png文件(image.png)。 dashLen为1时,它总是画一条实线。当dashlen为2时,通常绘制虚线长度为2的线,但是当xstart为5且ypos为10时绘制虚线(虚线长度为1)并给出不同的值当xstart为0.5且ypos为10时,结果取决于antiAlias是打开还是关闭。

是否需要使用另一个图形上下文设置才能使此功能适用于虚线?

保存为test.mm的编译代码: clang -framework Foundation -framework可可test.mm -o测试

运行代码: ./test

#import <Cocoa/Cocoa.h>

int main(int argc, char *argv[])
{
    float dashLen = 1;
    float xstart = 5;
    float ypos = 10.5;
    bool antiAlias = false;

    size_t width = 256;
    size_t height = 32;
    size_t bitsPerComponent = 8;
    size_t bytesPerPixel = 4;
    size_t bitsPerPixel = bytesPerPixel*8;
    size_t bytesPerRow = width * bytesPerPixel;
    size_t bufferLength = width * height * bytesPerPixel;
    void *bitmapData = malloc(height*bytesPerRow);
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
    CGColorSpaceRef colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
    CGContextRef offscreen = CGBitmapContextCreate(bitmapData,width,height,bitsPerComponent,bytesPerRow,colorSpace,bitmapInfo);

    CGContextSetShouldAntialias(offscreen, antiAlias);
    CGContextSetStrokeColorWithColor(offscreen, CGColorCreateGenericRGB(1,0,1,1));
    CGFloat dash[2] = { dashLen,dashLen };
    CGContextSetLineWidth(offscreen, 1.0f);
    CGContextSetLineDash(offscreen,0,dash,2);
    CGContextBeginPath(offscreen);
    CGContextMoveToPoint(offscreen, xstart, ypos);
    CGContextAddLineToPoint(offscreen, 240, ypos);
    CGContextClosePath(offscreen);
    CGContextStrokePath(offscreen);

    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmapData, bufferLength, NULL);
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;
    CGImageRef iref = CGImageCreate(width,height,bitsPerComponent,bitsPerPixel,bytesPerRow,colorSpace,bitmapInfo,provider,NULL,NO,renderingIntent);

    NSImage *image = [[NSImage alloc] initWithCGImage:iref size:NSMakeSize(width, height)];
    NSBitmapImageRep *imgRep = [[NSBitmapImageRep alloc] initWithCGImage:iref];
    NSDictionary* imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.3] forKey:NSImageCompressionFactor];
    NSData *data = [imgRep representationUsingType: NSPNGFileType properties: imageProps];
    [data writeToFile: @"image.png" atomically: NO];
    return 0;
}

0 个答案:

没有答案