|
1 | 1 | #import "RNSVGUIKit.h" |
| 2 | +#import <objc/runtime.h> |
2 | 3 |
|
3 | 4 | @implementation RNSVGView { |
4 | 5 | } |
@@ -57,3 +58,70 @@ - (CGPoint)CGPointValue |
57 | 58 | } |
58 | 59 |
|
59 | 60 | @end |
| 61 | + |
| 62 | +static char RCTGraphicsContextSizeKey; |
| 63 | + |
| 64 | +void RNSVGUIGraphicsBeginImageContextWithOptions(CGSize size, __unused BOOL opaque, CGFloat scale) |
| 65 | +{ |
| 66 | + if (scale == 0.0) { |
| 67 | + // TODO: Assert. We can't assume a display scale on macOS |
| 68 | + scale = 1.0; |
| 69 | + } |
| 70 | + |
| 71 | + size_t width = ceilf(size.width * scale); |
| 72 | + size_t height = ceilf(size.height * scale); |
| 73 | + |
| 74 | + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); |
| 75 | + CGContextRef ctx = CGBitmapContextCreate( |
| 76 | + NULL, |
| 77 | + width, |
| 78 | + height, |
| 79 | + 8 /*bitsPerComponent*/, |
| 80 | + width * 4 /*bytesPerRow*/, |
| 81 | + colorSpace, |
| 82 | + kCGImageAlphaPremultipliedFirst); |
| 83 | + CGColorSpaceRelease(colorSpace); |
| 84 | + |
| 85 | + if (ctx != NULL) { |
| 86 | + // flip the context (top left at 0, 0) and scale it |
| 87 | + CGContextTranslateCTM(ctx, 0.0, height); |
| 88 | + CGContextScaleCTM(ctx, scale, -scale); |
| 89 | + |
| 90 | + NSGraphicsContext *graphicsContext = [NSGraphicsContext graphicsContextWithCGContext:ctx flipped:YES]; |
| 91 | + objc_setAssociatedObject( |
| 92 | + graphicsContext, &RCTGraphicsContextSizeKey, [NSValue valueWithSize:size], OBJC_ASSOCIATION_COPY_NONATOMIC); |
| 93 | + |
| 94 | + [NSGraphicsContext saveGraphicsState]; |
| 95 | + [NSGraphicsContext setCurrentContext:graphicsContext]; |
| 96 | + |
| 97 | + CFRelease(ctx); |
| 98 | + } |
| 99 | +} |
| 100 | + |
| 101 | +void RNSVGUIGraphicsEndImageContext(void) |
| 102 | +{ |
| 103 | + RCTAssert( |
| 104 | + objc_getAssociatedObject([NSGraphicsContext currentContext], &RCTGraphicsContextSizeKey), |
| 105 | + @"The current graphics context is not a React image context!"); |
| 106 | + [NSGraphicsContext restoreGraphicsState]; |
| 107 | +} |
| 108 | + |
| 109 | +NSImage *RNSVGUIGraphicsGetImageFromCurrentImageContext(void) |
| 110 | +{ |
| 111 | + NSImage *image = nil; |
| 112 | + NSGraphicsContext *graphicsContext = [NSGraphicsContext currentContext]; |
| 113 | + |
| 114 | + NSValue *sizeValue = objc_getAssociatedObject(graphicsContext, &RCTGraphicsContextSizeKey); |
| 115 | + if (sizeValue != nil) { |
| 116 | + CGImageRef cgImage = CGBitmapContextCreateImage([graphicsContext CGContext]); |
| 117 | + |
| 118 | + if (cgImage != NULL) { |
| 119 | + NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:cgImage]; |
| 120 | + image = [[NSImage alloc] initWithSize:[sizeValue sizeValue]]; |
| 121 | + [image addRepresentation:imageRep]; |
| 122 | + CFRelease(cgImage); |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + return image; |
| 127 | +} |
0 commit comments