Core Graphics

RSS for tag

Harness the power of Quartz technology to perform lightweight 2D rendering with high-fidelity output using Core Graphics.

Core Graphics Documentation

Posts under Core Graphics tag

53 Posts
Sort by:
Post not yet marked as solved
0 Replies
344 Views
When zoom in, CATiledLayer works very well. It shows previous layer while rendering next layer. I cannot aware the rendering. When zoom out, it sucks. It leaves blank when rendering smaller scale layer. How can I solve this??? For example, when downscale, put the draw rect into main thread?
Posted Last updated
.
Post not yet marked as solved
4 Replies
736 Views
Yesterday, my code ran just fine under the previous Xcode version. Today, some print() statements seem to come with extra lines. I know it sounds stupid, but my code did not change in the meantime. It doesn't appear to come from anything I control, almost like some Apple code emits an extra line feed somewhere. It's just a Swift Mac App I built to make my digital art; otherwise, nothing else is incorrect, just these odd lines. It's not as simple as just making a test case with a few print("***") statements, it seems to require other code to run in between calls to print. Most of my app is using CoreGraphics. It has no UI. It's like when you see spurious Apple debugging info in the console sometimes, but it's only a blank line this time. It's not a big issue, just annoying.
Posted
by bigidle.
Last updated
.
Post not yet marked as solved
1 Replies
450 Views
I am trying to generate a PDF file with certain components draw with Spot Colours. Spot colours are used for printing and I am not clear on how one would do that but I think that if I can create a custom ColorSpace with a specific name or a color that has a specific name - our printer looks for the name Spot1 and they use the colour green. Can anyone shed any light on how I might be able to do this. For reference I have attached two pdf files with two different spot colours in them. I need to be able to create similar using CGContext and CGPDFDocument. I can already generate the PDF documents using CMYK colors but don't know how I can create the equivalent "spot" colors. At the moment I am loading the page from these attached pdf files and scaling them to fill the page to get a background with the spot color. This works fine but I also need to generate text and lines using this same spot color and I am not clear how I could do that using the Core Graphics APIs. My guess is I need to create a custom ColorSpace with a single color and then use that color for drawing with. The only 'custom' option for creating a ColorSpace seems to be the CGColorSpace(propertyListPList:) constructor, however there does not appear to be any documentation on what needs to be in the property list to do so. Nor can I find any examples of that. Any pointers would be appreciated. Regards
Posted
by duncang.
Last updated
.
Post not yet marked as solved
0 Replies
386 Views
I am trying to create a custom CGColorSpace in Swift on macOS but am not sure I really understand the concepts. I want to use a custom color space called Spot1 and if I extract the spot color from a PDF I get the following: "ColorSpace<Dictionary>" = { "Cs2<Array>" = ( Separation, Spot1, DeviceCMYK, { "BitsPerSample<Integer>" = 8; "Domain<Array>" = ( 0, 1 ); "Filter<Name>" = FlateDecode; "FunctionType<Integer>" = 0; "Length<Integer>" = 526; "Range<Array>" = ( 0, 1, 0, 1, 0, 1, 0, 1 ); "Size<Array>" = ( 1024 ); } ); }; How can I create this same color space using the CGColorSpace(propertyListPlist: CFPropertyList) API func createSpot1() -> CGColorSpace? { let dict0 : NSDictionary = [ "BitsPerSample": 8, "Domain" : [0,1], "Filter" : "FlateDecode", "FunctionType" : 0, "Length" : 526, "Range" : [0,1,0,1,0,1,0,1], "Size" : [1024]] let dict : NSDictionary = [ "Cs2" : ["Separation","Spot1", "DeviceCMYK", dict0] ] let space = CGColorSpace(propertyListPlist: dict as CFPropertyList) if space == nil { DebugLog("Spot1 color space is nil!") } return space }
Posted
by duncang.
Last updated
.
Post not yet marked as solved
1 Replies
509 Views
I want to read metadata of image files such as copyright, author etc. I did a web search and the closest thing is CGImageSourceCopyPropertiesAtIndex: - (void)tableViewSelectionDidChange:(NSNotification *)notif { NSDictionary* metadata = [[NSDictionary alloc] init]; //get selected item NSString* rowData = [fileList objectAtIndex:[tblFileList selectedRow]]; //set path to file selected NSString* filePath = [NSString stringWithFormat:@"%@/%@", objPath, rowData]; //declare a file manager NSFileManager* fileManager = [[NSFileManager alloc] init]; //check to see if the file exists if ([fileManager fileExistsAtPath:filePath] == YES) { //escape all the garbage in the string NSString *percentEscapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)filePath, NULL, NULL, kCFStringEncodingUTF8); //convert path to NSURL NSURL* filePathURL = [[NSURL alloc] initFileURLWithPath:percentEscapedString]; NSError* error; NSLog(@"%@", [filePathURL checkResourceIsReachableAndReturnError:error]); //declare a cg source reference CGImageSourceRef sourceRef; //set the cg source references to the image by passign its url path sourceRef = CGImageSourceCreateWithURL((CFURLRef)filePathURL, NULL); //set a dictionary with the image metadata from the source reference metadata = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(sourceRef,0,NULL); NSLog(@"%@", metadata); [filePathURL release]; } else { [self showAlert:@"I cannot find this file."]; } [fileManager release]; } Is there any better or easy approach than this?
Posted
by imneo.
Last updated
.
Post marked as solved
2 Replies
1.4k Views
I try to rotate a page 180° in a pdf file. I nearly get it, but the page is also mirrored horizontally. Some images to illustrate: Initial page: Result after rotation (see code): it is rotated 180° BUT mirrored horizontally as well: The expected result It is just as if it was rotated 180°, around the x axis of the page. And I would need to rotate 180° around z axis (perpendicular to the page). It is probably the result of writeContext!.scaleBy(x: 1, y: -1) I have tried a lot of changes for transform, translate, scale parameters, including removing calls to some of them, to no avail. @IBAction func createNewPDF(_ sender: UIButton) { var originalPdfDocument: CGPDFDocument! let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) let documentsDirectory = urls[0] // read some pdf from bundle for test if let path = Bundle.main.path(forResource: "Test", ofType: "pdf"), let pdf = CGPDFDocument(URL(fileURLWithPath: path) as CFURL) { originalPdfDocument = pdf } else { return } // create new pdf let modifiedPdfURL = documentsDirectory.appendingPathComponent("Modified.pdf") guard let page = originalPdfDocument.page(at: 1) else { return } // Starts at page 1 var mediaBox: CGRect = page.getBoxRect(CGPDFBox.mediaBox) // mediabox which will set the height and width of page let writeContext = CGContext(modifiedPdfURL as CFURL, mediaBox: &mediaBox, nil) // get the context var pageRect: CGRect = page.getBoxRect(CGPDFBox.mediaBox) // get the page rect writeContext!.beginPage(mediaBox: &pageRect) let m = page.getDrawingTransform(.mediaBox, rect: mediaBox, rotate: 0, preserveAspectRatio: true) // Because of rotate 0, no effect ; changed rotate to 180, then get an empty page writeContext!.translateBy(x: 0, y: pageRect.size.height) writeContext!.scaleBy(x: 1, y: -1) writeContext!.concatenate(m) writeContext!.clip(to: pageRect) writeContext!.drawPDFPage(page) // draw content in page writeContext!.endPage() // end the current page writeContext!.closePDF() } Note: This is a follow up of a previous thread, https://developer.apple.com/forums/thread/688436
Posted
by Claude31.
Last updated
.
Post not yet marked as solved
3 Replies
681 Views
CGImageRef __nullable CGImageCreate(size_t width, size_t height, size_t bitsPerComponent, size_t bitsPerPixel, size_t bytesPerRow, CGColorSpaceRef cg_nullable space, CGBitmapInfo bitmapInfo, CGDataProviderRef cg_nullable provider, const CGFloat * __nullable decode, bool shouldInterpolate, CGColorRenderingIntent intent) function returns null when kCGImageAlphaNone is passed for bitmap info with error message "verify_image_parameters: invalid image alphaInfo: kCGImageAlphaNone. It should be kCGImageAlphaNoneSkipLast" This issue happens only when installing on iOS 17 from XCode 15(Swift 5). Is it possible to fix this problem without having change the bitmap info as that can affect other parts of image processing.
Posted
by 20arnab00.
Last updated
.
Post not yet marked as solved
2 Replies
446 Views
SayI have a function that will receive a UIImage as an argument, perform the logic inside it and then return it updated So I came up with something like this: func processImage(image: UIImage?) -> UIImage? { if let image = image, let cgImage = image.cgImage { let width = cgImage.width let height = cgImage.height let colorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) if let context = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 4 * width, space: colorSpace, bitmapInfo: bitmapInfo.rawValue) { context.draw(cgImage, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height))) if let data = context.data { let buffer = data.bindMemory(to: UInt8.self, capacity: width * height * 4) for i in 0..<(width * height) { let pixelIndex = i * 4 let red = buffer[pixelIndex] let green = buffer[pixelIndex + 1] let blue = buffer[pixelIndex + 2] if isSystemGrayPixel(red: red, green: green, blue: blue) { // Convert systemGray to systemPink buffer[pixelIndex] = 255 // R component buffer[pixelIndex + 1] = 182 // G component buffer[pixelIndex + 2] = 193 // B component } } if let modifiedCGImage = context.makeImage() { let processedImage = UIImage(cgImage: modifiedCGImage) return processedImage } } } } return image } insde it I have called a helper function that will conditionally check if it contains .systemGrey and if so than change it as I func isSystemGrayPixel(red: UInt8, green: UInt8, blue: UInt8) -> Bool { let systemGrayColor = UIColor.systemBlue let ciSystemGrayColor = CIColor(color: systemGrayColor) let tolerance: CGFloat = 10.0 / 255.0 let redDiff = abs(ciSystemGrayColor.red - CGFloat(red) / 255.0) let greenDiff = abs(ciSystemGrayColor.green - CGFloat(green) / 255.0) let blueDiff = abs(ciSystemGrayColor.blue - CGFloat(blue) / 255.0) return redDiff <= tolerance && greenDiff <= tolerance && blueDiff <= tolerance } When I try to save it into a saveCanvas I will show in the console that the entry is saved but when i try to retrieve it later I will get nil This is my saveCanvas to serve as a reference @objc func saveCanvas(_ sender: Any) { guard let canvas = Canvas(name: "", canvas: mainImageView, numOfPages: 0) else { return } var savedImageView2 = UIImageView() savedImageView2.image = mainImageView.image?.copy() as? UIImage let updatedImage = processImage(image: savedImageView2.image) canvas.canvas.image = updatedImage // array that stores UIimageView gobally defined canvasArray.append(canvas) if canvasArray.count > 0 { canvasArray.forEach{ canvas in print("\(canvas.canvas == savedImageView )") print("clicked button \( canvasArray) ") } } } I am expecting to retrieve each iteration of canvasArray when i call it later in another function(which worked fine before I created the processImage function) . Like I said the purpose of processImage is to check if my UIImage contains .systemGrey and i so returned updated as I defined inside my isSystemGrayPixel function. Is there anything you might consider I do different rather do in my processImage to make it work as expected?
Posted
by AdelD.
Last updated
.
Post not yet marked as solved
0 Replies
325 Views
Translated Report (Full Report Below) Version: 1.0.0 (2.0) Code Type: X86-64 (Translated) Parent Process: launchd [1] User ID: 948009654 Date/Time: 2023-11-02 19:47:33.1522 +0800 OS Version: macOS 12.1 (21C52) Report Version: 12 Anonymous UUID: 815896E6-939E-002C-08C6-C903A4B87DF4 Sleep/Wake UUID: F06CECA0-3643-4423-A6F4-1163217FF863 Time Awake Since Boot: 100000 seconds Time Since Wake: 92675 seconds System Integrity Protection: enabled Crashed Thread: 0 CrBrowserMain Dispatch queue: com.apple.main-thread Exception Type: EXC_CRASH (SIGABRT) Exception Codes: 0x0000000000000000, 0x0000000000000000 Exception Note: EXC_CORPSE_NOTIFY Application Specific Information: Assertion failed: (mach_vm_map(mach_task_self(), &address, size, 0, VM_FLAGS_ANYWHERE | VM_MAKE_TAG(VM_MEMORY_COREGRAPHICS_BACKINGSTORES), port, 0, false, prot, prot, VM_INHERIT_SHARE) == KERN_SUCCESS), function backing_map, file CGSBackingStore.c, line 192. Kernel Triage: VM - Compressor failed a blocking pager_get VM - Compressor failed a blocking pager_get VM - Compressor failed a blocking pager_get VM - Compressor failed a blocking pager_get VM - Compressor failed a blocking pager_get Thread 0 Crashed:: CrBrowserMain Dispatch queue: com.apple.main-thread 0 <translation info unavailable> 0x108107a20 ??? 1 libsystem_kernel.dylib 0x7ff8023cd5e2 __sigreturn + 10 2 ??? 0x7fc103a4f190 ??? 3 libsystem_c.dylib 0x7ff80234dd10 abort + 123 4 libsystem_c.dylib 0x7ff80234d0be __assert_rtn + 314 5 SkyLight 0x7ff8075129de backing_map + 550 6 SkyLight 0x7ff8072c82ad lock_window_backing + 557 7 SkyLight 0x7ff807369f41 SLSDeviceLock + 54 8 CoreGraphics 0x7ff8076e6550 ripd_Lock + 56 9 CoreGraphics 0x7ff807678772 RIPLayerBltShape + 490 10 CoreGraphics 0x7ff8076769c7 ripc_Render + 328 11 CoreGraphics 0x7ff8076737d4 ripc_DrawRects + 482 12 CoreGraphics 0x7ff807673565 CGContextFillRects + 145 13 CoreGraphics 0x7ff8076734c4 CGContextFillRect + 117 14 CoreGraphics 0x7ff807672fe8 CGContextClearRect + 52 15 HIToolbox 0x7ff80b6176e0 HIMenuBarView::DrawOnce(CGRect, CGRect, bool, HIMenuBarTextAppearance, CGContext*) + 110 16 HIToolbox 0x7ff80b617640 HIMenuBarView::DrawIntoWindow(unsigned int*, CGRect, double, CGRect, bool, HIMenuBarTextAppearance, CGContext*) + 410 17 HIToolbox 0x7ff80b53c146 HIMenuBarView::DrawSelf(short, __HIShape const*, CGContext*) + 280 18 HIToolbox 0x7ff80b53bd56 HIMenuBarView::DrawingDelegateHandler(OpaqueEventHandlerCallRef*, OpaqueEventRef*, void*) + 262 19 HIToolbox 0x7ff80b520d1d DispatchEventToHandlers(EventTargetRec*, OpaqueEventRef*, HandlerCallRec*) + 1391 20 HIToolbox 0x7ff80b52014e SendEventToEventTargetInternal(OpaqueEventRef*, OpaqueEventTargetRef*, HandlerCallRec*) + 333 21 HIToolbox 0x7ff80b51ffef SendEventToEventTargetWithOptions + 45 22 HIToolbox 0x7ff80b53b8d3 HIView::SendDraw(short, OpaqueGrafPtr*, __HIShape const*, CGContext*) + 325 23 HIToolbox 0x7ff80b53b399 HIView::RecursiveDrawComposited(__HIShape const*, __HIShape const*, unsigned int, HIView*, CGContext*, unsigned char, double) + 571 24 HIToolbox 0x7ff80b53b56d HIView::RecursiveDrawComposited(__HIShape const*, __HIShape const*, unsigned int, HIView*, CGContext*, unsigned char, double) + 1039 25 HIToolbox 0x7ff80b53add8 HIView::DrawComposited(short, OpaqueGrafPtr*, __HIShape const*, unsigned int, HIView*, CGContext*) + 832 26 HIToolbox 0x7ff80b53aa89 HIView::Render(unsigned int, CGContext*) + 51 27 HIToolbox 0x7ff80b5521a9 FlushWindowObject(WindowData*, void**, unsigned char) + 772 28 HIToolbox 0x7ff80b551c2f FlushAllBuffers(__CFRunLoopObserver*, unsigned long, void*) + 317 29 CoreFoundation 0x7ff8024c6f98 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 23 30 CoreFoundation 0x7ff8024c6e34 __CFRunLoopDoObservers + 543 31 CoreFoundation 0x7ff8024c5830 CFRunLoopRunSpecific + 446 32 HIToolbox 0x7ff80b5474f1 RunCurrentEventLoopInMode + 292 33 HIToolbox 0x7ff80b547118 ReceiveNextEventCommon + 284 34 HIToolbox 0x7ff80b546fe5 _BlockUntilNextEventMatchingListInModeWithFilter + 70 35 AppKit 0x7ff804e1bb4c _DPSNextEvent + 886 36 AppKit 0x7ff804e1a1b8 -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1411 37 AppKit 0x7ff804e0c5a9 -[NSApplication run] + 586 38 libqcocoa.dylib 0x11402762f QCocoaEventDispatcher::processEvents(QFlags<QEventLoop::ProcessEventsFlag>) + 2495 39 QtCore 0x11ace2acf QEventLoop::exec(QFlags<QEventLoop::ProcessEventsFlag>) + 431 40 QtCore 0x11ace7042 QCoreApplication::exec() + 130 Anyone knows why it happens and how to fix it?
Posted
by mikucy.
Last updated
.
Post not yet marked as solved
11 Replies
4.7k Views
Hi team, We have an iOS app. Since July 15, 2022, our users met a kind of app crash due to an invalid memory fetch. The time is when Apple released iOS 16 beta officially. After Sep 12, crash count started to increase drastically. The time is Apple released iOS 16 officially. Crash backtrace can be seen as follows. Thread 14 Crashed: 0 libsystem_platform.dylib 0x00000001f8810930 _platform_memmove + 96 1 CoreGraphics 0x00000001adb64104 CGDataProviderCreateWithCopyOfData + 20 2 CoreGraphics 0x00000001adb4cdb4 CGBitmapContextCreateImage + 172 3 VisionKitCore 0x00000001ed813f10 -[VKCRemoveBackgroundResult _createCGImageFromBGRAPixelBuffer:cropRect:] + 348 4 VisionKitCore 0x00000001ed813cc0 -[VKCRemoveBackgroundResult createCGImage] + 156 5 VisionKitCore 0x00000001ed8ab6f8 __vk_cgImageRemoveBackgroundWithDownsizing_block_invoke + 64 6 VisionKitCore 0x00000001ed881474 __63-[VKCRemoveBackgroundRequestHandler performRequest:completion:]_block_invoke.5 + 436 7 MediaAnalysisServices 0x00000001eec58968 __92-[MADService performRequests:onPixelBuffer:withOrientation:andIdentifier:completionHandler:]_block_invoke.38 + 400 8 CoreFoundation 0x00000001abff0a14 __invoking___ + 148 9 CoreFoundation 0x00000001abf9cf2c -[NSInvocation invoke] + 428 10 Foundation 0x00000001a6464d38 __NSXPCCONNECTION_IS_CALLING_OUT_TO_REPLY_BLOCK__ + 16 11 Foundation 0x00000001a64362fc -[NSXPCConnection _decodeAndInvokeReplyBlockWithEvent:sequence:replyInfo:] + 520 12 Foundation 0x00000001a6a10f44 __88-[NSXPCConnection _sendInvocation:orArguments:count:methodSignature:selector:withProxy:]_block_invoke_5 + 188 13 libxpc.dylib 0x00000001f89053e4 _xpc_connection_reply_callout + 124 14 libxpc.dylib 0x00000001f88f8580 _xpc_connection_call_reply_async + 88 15 libdispatch.dylib 0x00000001b340205c _dispatch_client_callout3 + 20 16 libdispatch.dylib 0x00000001b341ff58 _dispatch_mach_msg_async_reply_invoke + 344 17 libdispatch.dylib 0x00000001b340956c _dispatch_lane_serial_drain + 376 18 libdispatch.dylib 0x00000001b340a214 _dispatch_lane_invoke + 436 19 libdispatch.dylib 0x00000001b3414e10 _dispatch_workloop_worker_thread + 652 20 libsystem_pthread.dylib 0x00000001f88a4df8 _pthread_wqthread + 288 21 libsystem_pthread.dylib 0x00000001f88a4b98 start_wqthread + 8 Last but not the least. The users who met this kind of app crash use iOS16+. We think this crash is related to iOS 16 SDK. We're appreciate that you can provide some clues how to fix this kind of crash.
Posted
by feiyz.
Last updated
.
Post not yet marked as solved
0 Replies
346 Views
This status is essential for generating simulated CGEvents. Games often use this API to implement cursor lock. If we send CGEvents with a moving position, it's possible for the cursor to move outside the game window and cause the game window to become inactive. If we don't send CGEvents with updated positions, we can only control the mouse within the game but not in other windows or the desktop.
Posted Last updated
.
Post not yet marked as solved
2 Replies
731 Views
Hello All, I am trying to compress PNG image by applying PNG Filters like(Sub, Up, Average, Paeth), I am applying filers using property kCGImagePropertyPNGCompressionFilter but there is no change seen in resultant images after trying any of the filter. What is the issue here can someone help me with this. Do I have compress image data after applying filter? If yes how to do that? Here is my source code CGImageDestinationRef outImageDestRef = NULL; long keyCounter = kzero; CFStringRef dstImageFormatStrRef = NULL; CFMutableDataRef destDataRef = CFDataCreateMutable(kCFAllocatorDefault,0); Handle srcHndl = //source image handle; ImageTypes srcImageType = //'JPEG', 'PNGf, etct; CGImageRef inImageRef = CreateCGImageFromHandle(srcHndl,srcImageType); if(inImageRef) { CFTypeRef keys[4] = {nil}; CFTypeRef values[4] = {nil}; dstImageFormatStrRef = CFSTR("public.png"); long png_filter = IMAGEIO_PNG_FILTER_SUB; //IMAGEIO_PNG_FILTER_SUB, IMAGEIO_PNG_FILTER_UP, IMAGEIO_PNG_FILTER_AVG, IMAGEIO_PNG_FILTER_PAETH .. it is one of this at a time keys[keyCounter] = kCGImagePropertyPNGCompressionFilter; values[keyCounter] = CFNumberCreate(NULL,kCFNumberLongType,&png_filter); keyCounter++; outImageDestRef = CGImageDestinationCreateWithData(destDataRef, dstImageFormatStrRef, 1, NULL); if(outImageDestRef) { // keys[keyCounter] = kCGImagePropertyDPIWidth; // values[keyCounter] = CFNumberCreate(NULL,kCFNumberLongType,&Resolution); // keyCounter++; // // keys[keyCounter] = kCGImagePropertyDPIHeight; // values[keyCounter] = CFNumberCreate(NULL,kCFNumberLongType,&Resolution); // keyCounter++; CFDictionaryRef options = CFDictionaryCreate(NULL,keys,values,keyCounter,&kCFTypeDictionaryKeyCallBacks,&kCFTypeDictionaryValueCallBacks); CGImageDestinationAddImage(outImageDestRef,inImageRef, options); CFRelease(options); status = CGImageDestinationFinalize(outImageDestRef); if(status == true) { UInt8 *destImagePtr = CFDataGetMutableBytePtr(destDataRef); destSize = CFDataGetLength(destDataRef); //using destImagePtr after this ... } CFRelease(outImageDestRef); } for(long cnt = kzero; cnt < keyCounter; cnt++) if(values[cnt]) CFRelease(values[cnt]); if(inImageRef) CGImageRelease(inImageRef); }
Posted Last updated
.
Post not yet marked as solved
0 Replies
760 Views
I have a SwiftUI view which consists on a horizontal scroll view with some pages inside. The elements of the pages project shadows. I noticed that when scrolling, as elements stop being visible, the shadow gets removed abruptly. The shadow itself is visible when it gets removed and it creates an unpleasant effect. I tried adding a transparent background to the element with the shadow that extends its frame to see if that way the shadow would be retained longer but it didn't work. Is there any workaround to make this behave the way I would like? Thanks in advance It seems it's not possible to post videos on the dev forums but I captured 3 frames of it showcasing the issue.
Posted
by 0xpablo.
Last updated
.
Post not yet marked as solved
4 Replies
391 Views
I'm am planning to use CoreGraphics for its low-level functionality, so I wrote up a small snippet that I expected to work: #include <CoreGraphics/CoreGraphics.h> int main() { double rot = CGDisplayRotation(0); printf("Rotation %f\n", rot); return 0; } Unfortunately, it seems that the call CGDisplayRotation blocks. When I tried writing a similar snippet in XCode though, it works just fine but I will not be able to use XCode for unrelated reasons. Am I compiling incorrectly? Could this be a permission issue? I compiled with clang -Wall -framework CoreGraphics core.c -o core.o
Posted
by Ian_L.
Last updated
.
Post not yet marked as solved
0 Replies
331 Views
Since the type identifiers in UTCoreTypes.h have been deprecated, what's the expected way to use the Core Graphics APIs that use those types, particularly in C code that doesn't have access to the UniformTypeIdentifiers framework? Using CFSTR( "public.jpeg" ) works, but is that the new best practice, or have the core type definitions been moved/renamed?
Posted
by dwn.
Last updated
.
Post not yet marked as solved
7 Replies
5.1k Views
On MacOSX 10.14 (Mojave) the behavior changed, the following code runs on 10.13 but fail on 10.14.The creation of "CGEventTapCreate" is failing (returning null) on Mojave but works before.Any thoughts? Thanks in advance!// alterkeys.c // http://osxbook.com // // Complile using the following command line: // clang -Wall -o alterkeys alterkeys.c -framework ApplicationServices // #include &amp;amp;lt;ApplicationServices/ApplicationServices.h&amp;amp;gt; // This callback will be invoked every time there is a keystroke. // CGEventRef myCGEventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) { // Paranoid sanity check. if ((type != kCGEventKeyDown) &amp;amp;amp;&amp;amp;amp; (type != kCGEventKeyUp)) return event; // The incoming keycode. CGKeyCode keycode = (CGKeyCode)CGEventGetIntegerValueField( event, kCGKeyboardEventKeycode); // Swap 'a' (keycode=0) and 'z' (keycode=6). if (keycode == (CGKeyCode)0) keycode = (CGKeyCode)6; else if (keycode == (CGKeyCode)6) keycode = (CGKeyCode)0; // Set the modified keycode field in the event. CGEventSetIntegerValueField( event, kCGKeyboardEventKeycode, (int64_t)keycode); // We must return the event for it to be useful. return event; } int main(void) { CGEventMask eventMask = CGEventMaskBit(kCGEventLeftMouseDown) | CGEventMaskBit(kCGEventLeftMouseUp); CFMachPortRef eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, 0, eventMask, myCGEventCallback, NULL); if (!eventTap) { fprintf(stderr, "failed to create event tap\n"); exit(1); } // Create a run loop source. CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource( kCFAllocatorDefault, eventTap, 0); // Add to the current run loop. CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); // Enable the event tap. CGEventTapEnable(eventTap, true); // Set it all running. CFRunLoopRun(); // In a real program, one would have arranged for cleaning up. exit(0); }
Posted
by alvarof.
Last updated
.
Post not yet marked as solved
1 Replies
1.4k Views
I needed an infinite canvas for my app which is basically a drawing board where one can draw things using pen. So, I thought of having a very large custom UIView inside a UIScrollView. And in the custom view, I could keep drawing things. But, I ended up with a warning saying something like below and nothing drawn on screen. [&lt;CALayer: 0x5584190&gt; display]: Ignoring bogus layer size (50000, 50000) Which means, I can't have such a big CALayer to draw things. Now, solution? alternative? Then comes CATiledLayer. I made my large UIView backed by CATiledLayer now. After having a proper levelOfDetails and levelOfDetailsBias value, things worked like charm. Until I ended up facing another problem. Since, CATiledLayer caches drawing in different zoom levels if I try to scale the view after changing the drawing content the cached drawings appear and then the new contents get drawn. I don't find an option to invalidate caches in different levels. All the solutions I came across leads me to clear the entire contents of the CATiledLayer on drawing content change which won't help again. Do I miss something here? Is there a way with which I can clear caches at different levels? Or is there any other solutions which could solve my need? Can someone help me with this?
Posted Last updated
.
Post not yet marked as solved
0 Replies
426 Views
I would like to get some information of the connected display such as vendor number, eisaId, … after connecting the external display via “screen mirroring” -&gt; “use as Separate Display” When the same display was connected through HDMI port or extend mode in screen mirroring, the information is not identical: HDMI Other display found - ID: 19241XXXX, Name: YYYY (Vendor: 19ZZZ, Model: 57WWW) Screen mirroring - extend mode Other display found - ID: 41288XX, Name: AAA (Vendor: 163ZYYBBB, Model: 16ZZWWYYY) I tried to get display information with the below method. func configureDisplays() { var onlineDisplayIDs = [CGDirectDisplayID](repeating: 0, count: 16) var displayCount: UInt32 = 0 guard CGGetOnlineDisplayList(16, &amp;onlineDisplayIDs, &amp;displayCount) == .success else { os_log("Unable to get display list.", type: .info) return } for onlineDisplayID in onlineDisplayIDs where onlineDisplayID != 0 { let name = DisplayManager.getDisplayNameByID(displayID: onlineDisplayID) let id = onlineDisplayID let vendorNumber = CGDisplayVendorNumber(onlineDisplayID) let modelNumber = CGDisplayModelNumber(onlineDisplayID) let serialNumber = CGDisplaySerialNumber(onlineDisplayID) if !DEBUG_SW, DisplayManager.isAppleDisplay(displayID: onlineDisplayID) { let appleDisplay = AppleDisplay(id, name: name, vendorNumber: vendorNumber, modelNumber: modelNumber, serialNumber: serialNumber, isVirtual: isVirtual, isDummy: isDummy) os_log("Apple display found - %{public}@", type: .info, "ID: \(appleDisplay.identifier), Name: \(appleDisplay.name) (Vendor: \(appleDisplay.vendorNumber ?? 0), Model: \(appleDisplay.modelNumber ?? 0))") } else { let otherDisplay = OtherDisplay(id, name: name, vendorNumber: vendorNumber, modelNumber: modelNumber, serialNumber: serialNumber, isVirtual: isVirtual, isDummy: isDummy) os_log("Other display found - %{public}@", type: .info, "ID: \(otherDisplay.identifier), Name: \(otherDisplay.name) (Vendor: \(otherDisplay.vendorNumber ?? 0), Model: \(otherDisplay.modelNumber ?? 0))") } } } Can we have the same display information when connect with an external display via HDMI port and extend mode in Screen Mirroring?
Posted
by lgminh.
Last updated
.