0

I am trying to create a bitmap copy of a view to use it as a drag shadow for a drag & drop operation.

I have used the techniques described here:

How to capture UIView to UIImage without loss of quality on retina display

How Do I Take a Screen Shot of a UIView?

How to get a color image in iPhone sdk (to render a solid fill into the view, resulted in an empty image too)

But the result is always a transparent/empty image (it's not nil/null, I checked)

The views I'm trying to copy contain (transparent) SVGs.

Here is my code:


    // always results in an fully transparent/empty image
    private UIView CreateDragShadow(UIView view)
    {
        UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, false, 0.0f);
        CGContext context = UIGraphics.GetCurrentContext();
        //view.DrawViewHierarchy(view.Bounds, true);    // "old" way
        view.Layer.RenderInContext(context);            // recommended way

        UIImage image = UIGraphics.GetImageFromCurrentImageContext();

        UIGraphics.EndImageContext();

        UIImageView dropShadow = new UIImageView();
        dropShadow.Image = image;

        return dropShadow;
    }

I have also written a little test function to see if the view gets added to the superview correctly, which works and correctly produces a white UIView with "Drag shadow" written on it:


    // this produces a white drag shadow image with "Drag shadow" written on it
    private UIView CreateDragShadowTest(UIView view)
    {
        // test with a simple UITextView to see if the approach works
        UITextView viewTestShadow = new UITextView(view.Frame);
        viewTestShadow.Bounds = view.Bounds;
        viewTestShadow.Text = "Drag shadow";

        return viewTestShadow;
    }

Does anybody know what's going on?

I'm also open to entirely different ways of doing this.

Best regards!

Community
  • 1
  • 1
bpylearner
  • 507
  • 4
  • 12

1 Answers1

0

I have since found an answer on the Xamarin documentation page that I couldn't find mentioned anywhere else when searching SO

The new code is:


    private UIView CreateDragShadow(UIView view)
    {                
        UIView dropShadow = view.SnapshotView(true);
        return dropShadow;
    }

Which exposes snapshotViewAfterScreenUpdates (found here: Apple Doc snapshotViewAfterScreenUpdates) and conveniently produces a UIView snapshot.

This solution has worked for me, but I would still like to know what I was doing wrong with the other approaches, if anybody knows.

bpylearner
  • 507
  • 4
  • 12