java - 缩小并绘制位图时长宽比关闭

标签 java android

我使用的图像来自 4x6。所以长宽比应该约为0.66。当我在代码中计算长宽比时,得到的值约为 0.66。然而,显示图像的高度看起来被压扁了。仅当我手动将纵横比设置为 0.85 左右时,图像才看起来正确。

由于手动设置宽高比并不完美,我怎样才能保持图像的高度不被挤压。

public class SpotGameActivity extends Activity {

private Bitmap mBitmap;

/** Called when the activity is first created. */


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dpi2b);
    setContentView(new BitMapView(this, mBitmap));

}

    class BitMapView extends View {
        Bitmap mBitmap = null;

        public BitMapView(Context context, Bitmap bm) {
            super(context);
            mBitmap = bm;
        }

        @Override
        protected void onDraw(Canvas canvas) {
            // called when view is drawn
            Paint paint = new Paint();
            paint.setFilterBitmap(true);
            // The image will be scaled so it will fill the width, and the
            // height will preserve the image’s aspect ration
            float aspectRatio = ((float) mBitmap.getWidth()) / mBitmap.getHeight();
            Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getHeight() * aspectRatio));

            String AR = Double.toString(aspectRatio);

            //Rect dest = new Rect(0, 0, getWidth(), getHeight());

            canvas.drawBitmap(mBitmap, null, dest, paint);
            Toast.makeText(SpotGameActivity.this, AR, Toast.LENGTH_SHORT).show();   
        }
    }

}

最佳答案

长宽比=宽度/高度

新高度=新宽度/宽高比

这样做,

Rect dest = new Rect(0, 0, this.getWidth(),(int) (this.getWidth() / aspectRatio));

关于java - 缩小并绘制位图时长宽比关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9716071/

相关文章:

Android:同时读取GPS + 加速计传感器

android - 在 RecyclerView 中滚动时自动在行之间添加空间

android - 如何像 Gallery 一样实现 Horizo​​ntalScrollView?

java - 如何设置使用 gridLayout 的 JPanel 最大或首选尺寸?

java - 使用 native 接口(interface)的多个 java 线程与多线程 native 的单个 java 线程

java - 我似乎无法修复 JApplet 错误

java - 对模块的模棱两可的调用

java - 处理器因任何原因停机时的 NiFi 数据安全

android - 使用支持库 v21 设置 SearchView 小部件的样式

java - 在 WebView 中缓存