返回

Android Bitmap

发布时间:2022-11-10 08:13:38 224
# 工具

Android Bitmap对象

这个例子实现的是点击按钮播放assets中的下一张图片。

public class MainActivity extends Activity {

/***************************************
* Bitmap代表一个位图对象,可以利用BitmapFactory来创建Bitmap对象。
* BitmapDrawable是对bitmap的封装,可以通过BitmapDrawable.getBitmap来获得。
* 多用BitmapFactory工具类来获得Bitmap对象。一个Bitmap对象就表示一张位图,在处理的时候要小心因为资源没有释放导致的问题
*
* Bitmap可以通过多种方法生成Bitmap对象,比如从资源文件中用decodeResource(res,id)
* decodeStream(stream) decodefile.可以把BitmapFactory看成一个中介。核心还是Bitmap。
* 这样的话ImageView才能用setImageBitmap
*
***************************************/
String images[] = null;
AssetManager assets = null;
int currentImg = 0;
ImageView imageView;
Button button;

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

imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);

assets = getAssets();
try {
images = assets.list("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

button.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

if (currentImg >= images.length) {
currentImg = 0;
}

// 找到下一个图片
while (!images[currentImg].endsWith("jpg")
&& !images[currentImg].endsWith("png")
&& !images[currentImg].endsWith("gif")) {

currentImg++;
if (currentImg >= images.length) {
currentImg = 0;
}
}
InputStream fileStream = null;// 不能在try里面定义。
try {
fileStream = assets.open(images[currentImg++]);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

BitmapDrawable bitmapDrawable = (BitmapDrawable) imageView
.getDrawable();
// 如果还未回收,强制回收
if (bitmapDrawable != null
&& !bitmapDrawable.getBitmap().isRecycled()) {
bitmapDrawable.getBitmap().recycle();
}
imageView.setImageBitmap(BitmapFactory.decodeStream(fileStream));
}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

 

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像
精选文章
thumb 中国研究员首次曝光美国国安局顶级后门—“方程式组织”
thumb 俄乌线上战争,网络攻击弥漫着数字硝烟
thumb 从网络安全角度了解俄罗斯入侵乌克兰的相关事件时间线
下一篇
通过U盘更新程序 2022-11-10 07:56:18