Scaling and translating a bitmap in android

不羁岁月 提交于 2019-11-30 17:14:52

问题


I am trying to sale a bitmap and translating it at each step.

If we look at the following code, I am drawing an image, translating and scaling it and then performing the same operations in reverse so as to get the original configuration back. But after applying the operations, I do get the original scaled image (scale factor 1) but the image is translated t a different position.

Could you please point out the correct method do so ? (In the example above, how do I reach the original configuration? )

 protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Matrix matrix = new Matrix();

        scale = (float)screenWidth/201.0f;
        matrix.setTranslate(-40, -40);
        matrix.setScale(scale, scale);

        canvas.drawBitmap(bitMap, matrix, paint);

        //back to original
        canvas.drawColor(0, Mode.CLEAR);
        matrix.setScale(1.0f/scale, 1.0f/scale);
        matrix.setTranslate(40,40);
        canvas.drawBitmap(bitMap, matrix, paint);

    }

回答1:


You should just use the Canvas methods for scaling and translating, that way you can then take advantage of the save() and restore() APIs to do what you need. For example:

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    //Save the current state of the canvas
    canvas.save();

    scale = (float) screenWidth / 201.0f;

    canvas.translate(-40, -40);
    canvas.scale(scale, scale);
    canvas.drawBitmap(bitMap, 0, 0, paint);

    //Restore back to the state it was when last saved
    canvas.restore();

    canvas.drawColor(0, Mode.CLEAR);
    canvas.drawBitmap(bitMap, 0, 0, paint);
}



回答2:


I think the problem with your original code might be because of the way scale and translate use the point around which you scale/translate. IF you specify the correct pivot points in between/for the operations, things will be ok.



来源:https://stackoverflow.com/questions/18709360/scaling-and-translating-a-bitmap-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!