一、概覽
當需要在應用程序中顯示靜態圖像時,可以使用drawable類及其子類來繪製形狀和圖像。drawable是可被繪製的內容的抽象。它的各種子類可用於特定的圖像場景,您可以擴展它們來定義您自己的drawable實現你想要的功能。
構建drawable對象:
1.構造方法 Drawable drawable = new ShapeDrawable();
2.加載項目裏的image資源
3.加載XML資源
注:在構建過程中,可以使用AAPT工具通過無損圖像壓縮自動優化放置在res/drawable/目錄中的圖像資源。例如,不需要超過256種顏色的真彩色PNG可以通過調色板轉換爲8位PNG。這會導致圖像質量相同,但需要的內存更少。因此,放置在此目錄中的映像二進制文件可以在生成時更改。如果計劃將圖像作爲位流讀取以將其轉換爲位圖,請將圖像放在res/raw/文件夾中,aapt工具不會修改它們。
demo1:使用drawable資源來創建image給imageView使用:
LinearLayout linearLayout;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create a LinearLayout in which to add the ImageView
linearLayout = new LinearLayout(this);
// Instantiate an ImageView and define its properties
ImageView i = new ImageView(this);
i.setImageResource(R.drawable.my_image);
// set the ImageView bounds to match the Drawable's dimensions
i.setAdjustViewBounds(true);
i.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
// Add the ImageView to the layout and set the layout as the content view
linearLayout.addView(i);
setContentView(linearLayout);
}
demo2:把圖片資源作爲drawable對象處理
Resources res = context.getResources();
Drawable myImage = ResourcesCompat.getDrawable(res, R.drawable.my_image, null);