BitMap和BitFactory

来源:互联网 发布:mysql不等于字符串 编辑:程序博客网 时间:2024/06/06 06:36

该实例从assets文件夹下读取图片文件,并且通过BitFactory的decodeStream方法设置为ImageView所显示的图片

首先复制几张图片到assets文件夹下,hehe.txt随便写的,测试用的


activity_main.java

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
    android:orientation="vertical">

    <ImageView android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
    <Button android:id="@+id/but"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="下一张"/>

</LinearLayout>

MainActivity.java

package com.example.bitmaptest;


import java.io.InputStream;


import android.os.Bundle;
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


public class MainActivity extends Activity {


AssetManager asset=null;
String[] imageList=null;
int currentIndex=0;

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

final ImageView imageView =(ImageView) super.findViewById(R.id.image);
Button but=(Button) super.findViewById(R.id.but);
final TextView text=(TextView) super.findViewById(R.id.text);

try {
//获取asssets下的所有文件
asset=getAssets();
   imageList=asset.list("");

but.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
//如果该文件不是图片,则currentIndex加1
while(!imageList[currentIndex].endsWith(".jpg")&&!imageList[currentIndex].endsWith(".png")&&!imageList[currentIndex].endsWith(".gif")){

currentIndex++;
if(currentIndex>=imageList.length){
currentIndex=0;
}
}

InputStream assetFile=null;
try {
//打开指定的资源对应的输入流
assetFile=asset.open(imageList[currentIndex]);
currentIndex++;

} catch (Exception e) {
e.printStackTrace();
}

BitmapDrawable bitmapDrawable=(BitmapDrawable) imageView.getDrawable();
//如果图片还未回收,先强制回收该图片
if(bitmapDrawable!=null&&bitmapDrawable.getBitmap().isRecycled()){
bitmapDrawable.getBitmap().recycle();
}
//改变ImageView显示的图片
imageView.setImageBitmap(BitmapFactory.decodeStream(assetFile));

}
});


} catch (Exception e) {
e.printStackTrace();
}

}

}

0 0
原创粉丝点击