簡體   English   中英

如何在這個簡單的 Android 應用程序中正確使用 Canvas 類將圖像顯示到 ImageView 中?

[英]How can I correctly use the Canvas class to show an image into an ImageView in this simple Android app?

我絕對是 Android 新手,我正在對Canvas對象進行一些實驗。

我正在嘗試將其添加到Canvas ,然后將其顯示到檢索到的ImageView 中(我知道這不是將圖像顯示到 ImageView 中的標准和最簡單的方法,但這只是針對更復雜的事情的簡化實驗)我必須使用Canvas )。

所以我有一個star.png (一個 32x32 像素的圖標到我的/res/drawable/文件夾中),我正在嘗試

這是我的activity_main.xml布局配置文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <ImageView
        android:id="@+id/star_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

此布局包含具有id=star_containerImageView ,這是我必須使用Canvas繪制圖像的地方

這是處理此視圖的MainActivity類:

public class MainActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        ImageView imgView = (ImageView) findViewById(R.id.star_container);

        Canvas canvas;

        Bitmap star = BitmapFactory.decodeResource(getResources(), R.drawable.star);
        Bitmap output = Bitmap.createBitmap(32, 32, Bitmap.Config.ARGB_8888);
        canvas = new Canvas(output);

        canvas.drawBitmap(star, star.getWidth() + 2, 0, null);

        imgView.setImageDrawable(new BitmapDrawable(getResources(), output));


    }
}

因此,在onCreate()方法中,我檢索了必須放置圖像的ImageView 然后我創建一個Bitmap對象,從資源中檢索star.png圖像,這些圖像將使用Canvas添加到otuput Bitmap 中。

最后,我將此輸出Bitmap 設置為檢索ImageView

所以我預計,當應用程序運行時,之前的ImageView包含star.png圖像但它沒有出現。

執行此應用程序時沒有錯誤,但我獲得的唯一輸出是定義到TextView 中的文本消息。

為什么? 怎么了? 我錯過了什么? 如何修改此代碼並讓它工作?

根據文件:

left:正在繪制的位圖左側的位置

問題在這里:

canvas.drawBitmap(star, star.getWidth() + 2, 0, null);

您正在使用超出位圖邊界的 left 值,因此沒有繪制任何內容,請嘗試以下操作: canvas.drawBitmap(star, 0, 0, null);

Android API 提供了另一種直接將Bitmap設置為drawable方法: ImageView#setImageBitmap(Bitmap bm)

我認為實現自定義View並在其中探索Canvas功能是更好的做法(在onDraw方法中)

另一種方式 - 使用矩形區域:

    Canvas canvas;

    Bitmap star = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    Bitmap output = Bitmap.createBitmap(star.getWidth(), star.getHeight(), Bitmap.Config.ARGB_8888);
    canvas  = new Canvas(output); 
    Rect source = new Rect(0, 0, star.getWidth(), star.getHeight());
    canvas.drawBitmap(star, null, source, null);    
    imgView.setImageBitmap(output);  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM