【问题标题】:Center in Canvas an scaled Bitmap inside public void onDraw(Canvas canvas)在 Canvas 中居中公共 void onDraw(Canvas canvas) 内的缩放位图
【发布时间】:2017-02-09 17:32:07
【问题描述】:

我设法缩放位图。

Rect src = new Rect(0, 0, icon.getWidth() - 1, icon.getHeight() - 1);
Rect dest = new Rect(0,0,Math.round(newWidth), Math.round(newHeight));
canvas.drawBitmap(icon, src, dest, null);

问题是图像出现在画布的左侧。 我希望它位于画布的中间。 一个大问题是我担心内存管理。所以我不想预先创建缩放位图,我更喜欢使用动态创建和绘制缩放位图的方法:

  canvas.drawBitmap(icon, src, dest, null);

我该怎么做?

【问题讨论】:

    标签: java canvas bitmap android-canvas


    【解决方案1】:

    如果您希望图像以Canvas为中心,只需计算中心坐标并将其应用于dest即可。

    int cx = (getWidth() - newWidth) / 2;
    int cy = (getHeight() - newHeight) / 2;
    
    Rect src = new Rect(0, 0, myBitmap.getWidth() - 1, myBitmap.getHeight() - 1);
    Rect dest = new Rect(cx, cy, cx+Math.round(newWidth), cy+Math.round(newHeight));
    canvas.drawBitmap(myBitmap, src, dest, null);
    

    但是,这样做不是正确的方法,因为每次调用 onDraw(Canvas) 时都会创建 2 个 Rect。只要 gc 垃圾收集它,它就会留在内存中。

    为避免这种情况,您可以预先计算 Rect 并存储它们,因为它们不像 Bitmap 在内存中那么重。

    【讨论】:

    • 你太棒了
    • 感谢您的夸奖。
    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-14
    相关资源
    最近更新 更多