简体   繁体   中英

Android Canvas.drawBitmap: How to draw right part of an image?

I would like to draw the right part of an image, but the result is alwas a stretched image of the entire bitmap, or a stretched part of the center of the bitmap. What am I doing wrong here?

int width;
int percentToDraw;
Random rand = new Random();
percentToDraw = rand.nextInt(100);
width = bmp.getWidth() * (100 - percentToDraw) / 100;

src = new Rect();
src.top = 0;
src.bottom = bmp.getHeight();
src.right = bmp.getWidth();
src.left = src.right - width;

dst = new Rect;
dst.top = getHeight() / 2 - bmp.getHeight() / 2;
dst.bottom = dst.top + (src.bottom - src.height);
dst.right = getWidth() / 2 + bmp.getWidth() / 2;
dst.left = dst.right - width;

canvas.drawBitmap(bmp, src, dst, paint);

I have been fiddling and googling about this for two days now, widthout finding anything close to a solution :-(

In case anyone else stumbles over this, I have been unable to make it work "correctly" but I've found a working solution using clipRect:

        int width;
        width = (int) Math.floor(bmp.getWidth() * percentToDraw / 100.0);
        src = new Rect();
        src.top = 0;
        src.bottom = bmp.getHeight();
        src.left = 0;
        src.right = bmp.getWidth();

        dst = new Rect();
        dst.top = getHeight() / 2 - bmp.getHeight() / 2;
        dst.bottom = dst.top + (src.bottom - src.top);
        dst.left = getWidth() / 2 - bmp.getWidth() / 2;
        dst.right = dst.left + (src.right - src.left);

        canvas.clipRect(dst.right - width, 0, getWidth(), getHeight(), Region.Op.REPLACE);
        canvas.drawBitmap(bmp, src, dst, paint);
        canvas.clipRect(0, 0, getWidth(), getHeight(), Region.Op.REPLACE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM