Android Canvas如何缩放和居中矩形

时间:2019-04-12 16:04:50

标签: android

我正在为Android编写简单的棋盘游戏。我想让游戏更适合不同的屏幕分辨率。所以我尝试缩放板子(9x9矩形)。我的问题是如何缩放板或矩形并保持中心?

我要附加一个带有矩形和图片的简单示例。

 public RectangleExample(Context c)
    {
        super(c);
    }

    final int width = 100 ;
    final int height = 100 ;
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.scale(1.5f, 1.5f);
        Paint paint = new Paint() ;
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);
        int startX = (getWidth() - width) / 2 ;
        int startY = (getHeight() - height) / 2 ;
        Rect r = new Rect(startX, startY, startX + width, startY + height);
        canvas.drawRect(r, paint);
    }

enter image description here

图片显示缩放矩形后失去中心。

1 个答案:

答案 0 :(得分:0)

尝试将坐标系原点移动(平移)到视图中心 并且只有在那之后应用缩放

类似的东西

final int width = 100;
final int height = 100;
final Paint paint = new Paint();

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.save();
    canvas.translate(getWidth() / 2, getHeight() / 2);
    canvas.scale(1.5f, 1.5f);
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    int startX = -width / 2;
    int startY = -height / 2;
    Rect r = new Rect(startX, startY, startX + width, startY + height);
    canvas.drawRect(r, paint);
    canvas.restore();
}

或者您可以设置枢轴点的坐标

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.scale(1.5f, 1.5f, getWidth() / 2, getHeight() / 2); // <---- here is
    Paint paint = new Paint() ;
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL_AND_STROKE);
    int startX = (getWidth() - width) / 2 ;
    int startY = (getHeight() - height) / 2 ;
    Rect r = new Rect(startX, startY, startX + width, startY + height);
    canvas.drawRect(r, paint);
}