android - 自定义 View 位图的大小不正确

标签 android view bitmap

我想在自定义 View 中加载特定大小的位图。作为第一步,我想在 400px x 400px View 中加载 400px x 400px 位图...但是加载的位图尺寸较小。

我发现了一些有类似问题的线程。建议使用 Options.inScale = false。我使用它,并获得了更好的日志消息(位图输出正确大小 400px x 400px),但它仍然呈现得更小:

enter image description here

(黄色是自定义 View 的背景 - 400px x 400px,红色是位图)。

有什么建议吗?这是代码:

自定义 View :

class TestView extends View {
    private Bitmap bitmap;
    private Paint paint = new Paint();

    public TestView(Context context) {
        super(context);
    }

    public TestView(Context context, AttributeSet attr) {
        super(context, attr);

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = false;

        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.overlay, options).copy(Config.ARGB_8888, true);  
        Log.d("test6", "width: " + bitmap.getWidth() + " height: " + bitmap.getHeight());
    }

    @Override
    public void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, 0, 0, paint);
    }
}

XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#000000"
    >
    <com.example.TestView
        android:id="@+id/view"
        android:layout_width="400px"
        android:layout_height="400px"
        android:background="#ffff00"
        />
</RelativeLayout>

位图已经是 400px x 400px ...这就是为什么我认为我不必使用缩放选项等的原因。我只想在屏幕上以这个尺寸显示它...

最佳答案

很可能您的 Bitmap 不在 drawable-nodpi 文件夹中,这就是它被缩放的原因。

根据 Canvas.drawBitmap 的文档:

If the bitmap and canvas have different densities, this function will take care of automatically scaling the bitmap to draw at the same density as the canvas.

关于android - 自定义 View 位图的大小不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15410648/

相关文章:

android - 如何从 URL 加载图像到 viewpager

php - 从数据库表android中获取行

java - 致命异常 : main android in google play services

java - 嵌套 SQL 语句或 View ?什么是理想的?

model-view-controller - 在joomla的 View 中调用模型函数?

c++ - AlphaBlend 生成不正确的颜色

Android - 改变 margin 问题?

android - 如何在 flutter 中获取小部件的坐标、比例和旋转数据?

php - 初始化 View 、模板和 Controller 以及模型是可选的

android - 位图压缩不会改变位图字节大小