在android中缩放和翻译位图

Use*_*r42 5 scaling android bitmap image-processing

我正在尝试销售位图并在每一步翻译它.

如果我们查看以下代码,我正在绘制图像,翻译和缩放它,然后反向执行相同的操作,以便恢复原始配置.但是在应用这些操作之后,我确实获得了原始的缩放图像(比例因子1),但是图像被翻译到不同的位置.

你能指出正确的方法吗?(在上面的示例中,如何到达原始配置?)

 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);

    }
Run Code Online (Sandbox Code Playgroud)

kco*_*ock 6

您应该只使用这些Canvas方法进行缩放和翻译,这样您就可以利用save()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);
}
Run Code Online (Sandbox Code Playgroud)