CGContextSetLineDash не работает с пунктирной линией - PullRequest
0 голосов
/ 17 сентября 2018

Я пытаюсь нарисовать пунктирную линию размером в один пиксель, используя CGContextSetLineDash на Mac, используя Mac OS X SDK 10.12. Приведенный ниже код рисует линию в контексте растрового изображения, а затем сохраняет растровое изображение в png-файле (image.png). Когда dashLen равен 1, он всегда рисует сплошную линию. Когда dashlen равен 2, он обычно рисует линию с длиной тире 2, но рисует пунктирную линию (длина тире 1), когда xstart равен 5, а ypos равен 10 и дает другие результаты, когда xstart равен 0,5 и ypos равно 10 в зависимости от того, включен или выключен antiAlias.

Есть ли другой параметр графического контекста, который необходимо применить, чтобы эта работа работала для пунктирной линии?

Код компиляции, сохраненный как test.mm: clang -framework Foundation -framework Какао test.mm -o test

Выполнить код: ./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;
}
...