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 <ApplicationServices/ApplicationServices.h>
// 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) && (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);
}
Core Graphics
RSS for tagHarness the power of Quartz technology to perform lightweight 2D rendering with high-fidelity output using Core Graphics.
Posts under Core Graphics tag
53 Posts
Sort by:
Post
Replies
Boosts
Views
Activity
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.
[<CALayer: 0x5584190> 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?
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
I really love Quartz Composer from Apple which is a quite old app, not updated for years. It works well on my 2015 mid MacBook Pro, but not on new M1 iMac. Does anyone know how to run this great app on my new machine? Thank you!
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.
I'm using CoreGraphics and Image I/O in a MacOS command-line tool. My program works fine, but after the first drawing to a bitmap context there are messages output to the console like the following:
2022-12-20 16:33:47.824937-0500 RandomImageGenerator[4436:90170] Metal API Validation Enabled
AVEBridge Info: AVEEncoder_CreateInstance: Received CreateInstance (from VT)
AVEBridge Info: connectHandler: Device connected (0x000000010030b520)Assert - (remoteService != NULL) - f: /AppleInternal/Library/BuildRoots/43362d89-619c-11ed-a949-7ef33c48bc85/Library/Caches/com.apple.xbs/Sources/AppleAVEBridge/AppleAVEEncoder/AppleAVEEncoder.c l: 291
AVE XPC Error: could not find remote service
Assert - (err == noErr) - f: /AppleInternal/Library/BuildRoots/43362d89-619c-11ed-a949-7ef33c48bc85/Library/Caches/com.apple.xbs/Sources/AppleAVEBridge/AppleAVEEncoder/AppleAVEEncoder.c l: 1961
AVE ERROR: XPC failed
AVEBridge Info: stopUserClient: IOServiceClose was successful.
AVEBridge Error: AVEEncoder_CreateInstance: returning err = -12908
These messages get in the way of my own console output. How do I stop these messages from being displayed?
This post on StackOverflow (https://stackoverflow.com/questions/37800790/hide-strange-unwanted-xcode-logs) does not appear to be relevant to this issue.
I'm trying to resize NSImages on macOS. I'm doing so with an extension like this.
extension NSImage {
// MARK: Resizing
/// Resize the image to the given size.
///
/// - Parameter size: The size to resize the image to.
/// - Returns: The resized image.
func resized(toSize targetSize: NSSize) -> NSImage? {
let frame = NSRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
guard let representation = self.bestRepresentation(for: frame, context: nil, hints: nil) else {
return nil
}
let image = NSImage(size: targetSize, flipped: false, drawingHandler: { (_) -> Bool in
return representation.draw(in: frame)
})
return image
}
}
The problem is, as far as I can tell, the image that comes out of the drawing handler has lost the original color profile of the original image rep. I'm testing it with a wide color gamut image, attached.
This becomes pure red when examing the image result.
If this was UIKit I guess I'd use the UIGraphicsImageRenderer and select the right UIGraphicsImageRendererFormat.Range and so I'm suspecting I need to use the NSGraphicsContext here to do the rendering but I can't see what on that I would set to make it use wide color or how I'd use it?
Rectangle()
.fill(
RadialGradient.radialGradient(
colors: [.blue, .yellow],
center: UnitPoint(x:0.5, y:0.5),
startRadius: 0,
endRadius: 50)
)
.frame(width: 100, height: 100)
In the above code I have a Rectangle with simple radial gradient as follow:
I wanna apply an arbitrary transformation matrix to the gradient so I can achieve following effects:
I tried following.. but it applying the transformation matrix to frame instead of shader/gradient
Rectangle()
.overlay(
RadialGradient.radialGradient(
colors: [.blue, .yellow],
center: UnitPoint(x:0.5, y:0.5),
startRadius: 0,
endRadius: 50)
.transformEffect(
CGAffineTransform(
-0.5000000596046448, 0.4999999403953552,
-0.972577691078186, -0.9725777506828308,
0.5000000596046448, 1.4725778102874756)
.translatedBy(x: -50, y: -100)
)
)
.frame(width: 100, height: 100)
it result in transformation of frame intreat of shader/gradient:
Thanks in advance 🙌🏻
Hello there,
I am building an app that's going to be keyboard oriented, meaning that the UI will be minimal and only live n the menu bar; all core functions will be performed from the keyboard hotkeys that should be available from wherever in the system.
I know about a Swift library called Hotkey that's doing it and it seems to work, however it uses the Carbon API which is deprecated for many years, plus its code is double dutch to me and, since it relies on a legacy code I wish I could atleast understand it to maintain my version of it in case MacOS finally sheds of the Carbon API completely. Is there a way to realize global hotkey in a more modern way?
Hi all:
I have a macOS application which capture mouse events:
CGEventMask eventMask = CGEventMaskBit(kCGEventMouseMoved) |
CGEventMaskBit(kCGEventLeftMouseUp) |
CGEventMaskBit(kCGEventLeftMouseDown) |
CGEventMaskBit(kCGEventRightMouseUp) |
CGEventMaskBit(kCGEventRightMouseDown) |
CGEventMaskBit(kCGEventOtherMouseUp) |
CGEventMaskBit(kCGEventOtherMouseDown) |
CGEventMaskBit(kCGEventScrollWheel) |
CGEventMaskBit(kCGEventLeftMouseDragged) |
CGEventMaskBit(kCGEventRightMouseDragged) |
CGEventMaskBit(kCGEventOtherMouseDragged);
_eventTap = CGEventTapCreate(kCGHIDEventTap,
kCGHeadInsertEventTap,
kCGEventTapOptionDefault,
eventMask,
&MouseCallback,
nil);
_runLoopRef = CFRunLoopGetMain();
_runLoopSourceRef = CFMachPortCreateRunLoopSource(NULL, _eventTap, 0);
CFRunLoopAddSource(_runLoopRef, _runLoopSourceRef, kCFRunLoopCommonModes);
CGEventTapEnable(_eventTap, true);
CGEventRef MouseCallback(CGEventTapProxy proxy,
CGEventType type,
CGEventRef event,
void *refcon) {
NSLog(@"Mouse event: %d", type);
return event;
}
This mouse logger need accessibility privilege granted in Privacy & Security. But I found that if accessibility turned off while CGEventTap is running, left & right click are blocked, unless restart macOS.
Although replace kCGEventTapOptionDefault to kCGEventTapOptionListenOnly can fix this issue, but I have other feature which require kCGEventTapOptionDefault.
So I try to detect accessibility is disabled and remove CGEventTap:
[[NSDistributedNotificationCenter defaultCenter] addObserver:self
selector:@selector(didToggleAccessStatus:)
name:@"com.apple.accessibility.api"
object:nil
suspensionBehavior:NSNotificationSuspensionBehaviorDeliverImmediately];
}
However, the notification won't be sent if user didn't turn off accessibility but removed it from list. Worse, AXIsProcessTrusted() continues to return true.
Is there a way to fix mouse blocked, or detect accessibility removed?
Thanks!
I would like to get some information of the connected display such as vendor number, eisaId, … after connecting the external display via “screen mirroring” -> “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, &onlineDisplayIDs, &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?
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?
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
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.
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);
}
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.
I'm attaching the crash log, hopefully someone can help me out. Thanks!
crashlog.crash
How can I take the contents (i.e. the stroke and fill) of a CAShapeLayer and draw it into an MTLTexture, which can then be displayed with a normal vertex/fragment shader?
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?
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?