main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/iv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/longshuai" <!-- longshuai.png為圖片的名稱,記在資源文件里頭,不用文件名后綴-->
/>
</LinearLayout>
注意:強(qiáng)調(diào)一下,資源文件的圖片命名規(guī)則比較嚴(yán)格,由[a-z]和數(shù)字和“_”組成,而且不能數(shù)字開頭,我就常犯傻,命名老是數(shù)字或者大寫字母開頭,這種錯(cuò)誤——囧。。
我們要把longshuai.png導(dǎo)入到res中,最簡單的方式就是直接找到這個(gè)文件夾,復(fù)制進(jìn)去
之后右鍵更新,我們就可以在res中看到自己的圖片了
不用寫代碼。。直接用自動(dòng)生成的代碼。。
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
效果如下:
2、加載本地圖片(其實(shí)主要是SdCard中圖片)
關(guān)于SdCard的使用,可以參見 http://longshuai2007.blog.163.com/blog/static/1420944142011611103950500/
xml文件同上面的是一樣的,并不需要修改
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView image1 = (ImageView) findViewById(R.id.iv1); //獲得ImageView對(duì)象
/*為什么圖片一定要轉(zhuǎn)化為 Bitmap格式的!! */
Bitmap bitmap = getLoacalBitmap("/sdcard/tubiao.jpg"); //從本地取圖片(在cdcard中獲取) //
image1 .setImageBitmap(bitmap); //設(shè)置Bitmap
}
/**
* 加載本地圖片
* @param url
* @return
*/
public static Bitmap getLoacalBitmap(String url) {
try {
FileInputStream fis = new FileInputStream(url);
return BitmapFactory.decodeStream(fis); ///把流轉(zhuǎn)化為Bitmap圖片
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
}
顯示效果如下:
只有注冊(cè)用戶登錄后才能發(fā)表評(píng)論。 | ||
![]() |
||
網(wǎng)站導(dǎo)航:
博客園
IT新聞
Chat2DB
C++博客
博問
管理
|
||