misho misho - 3 months ago 24
Objective-C Question

IKImageView image not visible while printing

I have

NSSplitView
with two
IKImageView
on both sides to compare them with each other. I'm trying to implement Print functionality but images disappear on preview. (What should be printed vs What I get)

What I tried:

Based on docs, locking focus on
splitView
and directly printing it with

[[NSPrintOperation printOperationWithView:view] runOperation];


But as long as docs state that


If UI contains multiple views that can have focus view-based printing doesn’t work well.


I tried making a "screenshot"(Method 1, Method 2) of the
splitView
, creating new
viewController
with single
NSImageView
, displaying my screenshot there and then printing imageView. But images weren't visible even in screenshot neither.

Important thing is that printing works just fine if I use
NSImageViews
instead of
IKImageViews
.

What else can I try?(Both
objective-c
and
swift
solutions would work)

Answer

Finally found a workaround to get it working(Also takes into account a zoom level). I get NSImages from IKImageViews, pass them to new ViewController where I show a preview of what will be printed. In that viewcontroller I have a simple NSView(rootView) with two NSImagesViews side by side. I set my images from IkImageViews to NSImageViews and then print the rootView.

Here is how I get NSImages from IkImageViews:

Steps: Get visible/cropped/zoomed rect from IkImageView; Create NSImage from IKImageView's CGImageRef; Create new NSImage and draw cropped image into it.

Note: obj-c syntax might be a bit wrong, I have never written even a single line of obj-c before(Xamarin Developer).

Objective-c:

NSRect croppedRect = [imageView convertViewRectToImageRect:[imageView visibleRect]];
NSImage srcImage = [[NSImage alloc] initWithCGImage:[imageView image] size:NSZeroSize];
NSImage croppedImage = [[NSImage alloc] initWithSize:croppedRect.size];
[croppedRect lockFocus];
[srcImage drawAtPoint:NSZeroPoint
          fromRect:croppedRect
          operation:NSCompositeCopy
          fraction:1.0];
[croppedRect unlockFocus];
return croppedImage;

C#(Xamarin):

NSImage GetImageToPrint()
    {
        var cropRect = LeftImage.ConvertViewRectToImageRect(LeftImage.VisibleRect());

        NSImage srcImage = new NSImage(LeftImage.Image, LeftImage.ImageSize);
        NSImage croppedImage = new NSImage(cropRect.Size);
        croppedImage.LockFocus();
        srcImage.Draw(CGPoint.Empty, cropRect, NSCompositingOperation.Copy, 1.0f);
        croppedImage.UnlockFocus();

        return croppedImage;
    }

Hope anyone will find the answer useful.

Comments