问题
I have a DialogFragment
that creates an AlertDialog
with a custom view in onCreateDialog
. The custom view includes a spinning progress bar and a prompt as well as a large view (larger than screen dimensions) that is fit inside the custom content via scaleX
and scaleY
values.
I am using the PixelCopy
API to copy only the large view into a bitmap. This works well, but with a rather annoying caveat:
I call PixelCopy
as such:
val winloc = intArrayOf(0, 0)
view.getLocationOnScreen(winloc)
val offset = 0
val left = winloc[0] + offset
val top = winloc[1] + offset
val rect = Rect(left, top, left + view.measuredWidth, top + view.measuredHeight)
PixelCopy.request(getDialog().getWindow(), rect, bitmap, listener, view.handler)
The view.getLocationOnScreen(winloc)
returns x and y coordinates of (84, 84)
When I check the generated bitmap, PixelCopy
has captured a whole lot of frame, padding, shadows, and the actual view content (with a bit missing from bottom right). The part of the actual content that is missing is exactly the same amount as the frame, padding, and shadow that I get at the top left of the image.
Having tried anything else I could think of to get the correct bounds of this content I want to save, I started adding random values to the coordinates (the offset
value above). On a Nexus 6P an offset of 112
was perfect. Now I can't just throw 112
in there without reason because 1. it's a magic number and 2. it only works on one device.
I have ran out of ideas as to how I can get the correct bounds for this view OR where I can find this 112
value so that I can properly offset what I have.
As the app is unreleased, I can't include actual screenshots, but here are some redacted screenshots (ignore the black bars).
Some notes about the screenshots:
- The green part comes from
dialog!!.window!!.setBackgroundDrawable(ColorDrawable(0xff00ff00.toInt()))
so I could outline the window bounds. The transparent/shadow bit between the screen edges and the green rectangle ... is this a margin or padding? - The white rectangle with the red (content 1) and the blue (content 2) rectangles is the portion going to the bitmap
- The red and the blue rectangles within the content are different views generated from the same data.
- The blue portion contains a few
SurfaceView
s that I suspect I'd have to extract separately.
Device screenshot
Captured Bitmap (without the 112
magic number offset)
回答1:
The solution so far has been to ditch the DialogFragment
and use a regular Fragment
. After inspecting the layouts, there were two paddings of 56
pixels, without any accessors to get their values. I suspect there's a bug somewhere in the private decor views that doesn't account for these paddings when calculating the location of the view in window.
I'll mark this as the answer until a better answer comes along.
来源:https://stackoverflow.com/questions/53550406/using-pixelcopy-to-copy-a-scaled-view-within-a-dialogfragment