1

I have a view I need to flip vertically, or mirror. There's plenty of information out there about mirroring a single bitmap by scaling it by -1 and translating for the offset, as described here, but there doesn't seem to be any information on how to draw all the contents of a View - specifically, all of it's subviews - upside down.

I have multiple subviews in this container - text, images - and I was hoping for a way that would let me just add them to a single View and draw that View upside down/sideways, rather than having them all perform custom drawing code to draw them upside down and have the container reposition them all appropriately. Any ideas?

Community
  • 1
  • 1
Xono
  • 1,900
  • 17
  • 20

2 Answers2

2

You could simply create a Canvas out of a Bitmap and then invoke your root view's View.draw(Canvas) method. This will give you a snapshot of the view hierarchy in a Bitmap. You then apply the aforementioned transformations to mirror the image.

zienkikk
  • 2,404
  • 1
  • 21
  • 28
  • I presume using it this way I'll need to recreate the bitmap on any change, such a button entering/leaving highlighted state? – Xono Sep 13 '12 at 02:52
  • Xono, that is correct. Although if you know exactly what changed then with help of some math you only have to redraw the rectangle that contains the change. This is not trivial, however. – zienkikk Sep 13 '12 at 17:24
  • Sounds like overkill for the situation, this would only be updating on touch down/up. A possible problem, though: since this view contains buttons, will input on the view have to adjusted as well? Simply flipping what's rendered won't change the actual button's positions, so won't touches go to the wrong section of the view? – Xono Sep 14 '12 at 01:20
1

Transfer View into Bitmap, then flip it using method below:

private static Bitmap getBitmapFromView(View view,int width,int height) {
    int widthSpec = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
    int heightSpec = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
    view.measure(widthSpec, heightSpec);
    view.layout(0, 0, width, height);
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    view.draw(canvas);

    return bitmap;
}


private static Bitmap flipBitmap(Bitmap src)
{
    Matrix matrix = new Matrix();
    matrix.preScale(-1, 1);
    Bitmap dst = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, false);
    dst.setDensity(DisplayMetrics.DENSITY_DEFAULT);
    return dst;
}
sam.wang.0723
  • 321
  • 1
  • 7