前言:
众所周知,决定一个Android应用是否可以被用户接受最重要的方面就是用户界面,为了让我们的Android给用户提供一个更友好的界面,就需要我们在应用中使用和插入图片了。Android系统提供了丰富的图片功能支持,其中就包括处理静态图片和动画等等。
一、使用简单的图片
(1)使用Drawable对象
为Android应用添加了Drawable资源之后,Android SDK会为这份资源在R清单文件中创建一个索引项:R.drawable.file_name。
接下来即可在XML资源文件中通过@drawable/file_name访问该Drawable对象,也可以在Java代码中通过R.drawable.file_name访问改对象。
(2)Bitmap和BitmapFactory
Bitmap代表一个位图,而BitmapDrawable中封装的图片就是一个Bitmap对象,开发者为了把一个Bitmap对象包装成BitmapDrawable对象,可以调用BitmapDrawable的构造器:
BitmapDrawable drawable = new BitmapDrawable(bitmap);
果需要获取BitmapDrawable所包装的Bitmap对象,则可调用 BitmapDrawable中的getBitmap()方法:
Bitmap bitmap = drawable.getBitmap();
(3)下面我们用以上知识实现一个图片查看器
我们这个应用十分简单,仅仅包括一个按钮和一个ImageView,当我们点击按钮时候,程序会自动去搜索目录中的下一张图片:
关键代码如下:
import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends Activity
{
String[] images = null;
AssetManager assets = null;
int currentImg = 0;
ImageView image;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
image = (ImageView) findViewById(R.id.image);
try
{
assets = getAssets();
// 获取目录下所有文件(assets下)
images = assets.list("");
}
catch (IOException e)
{
e.printStackTrace();
}
final Button next = (Button) findViewById(R.id.next);
// 为next按钮绑定事件监听器,该监听器将会查看下一张图片
next.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View sources)
{
if (currentImg >= images.length)
{
currentImg = 0;
}
// 找到下一个图片文件
while (!images[currentImg].endsWith(".png")
&& !images[currentImg].endsWith(".jpg")
&& !images[currentImg].endsWith(".gif"))
{
currentImg++;
if (currentImg >= images.length)
{
currentImg = 0;
}
}
InputStream assetFile = null;
try
{
assetFile = assets.open(images[currentImg++]);
}
catch (IOException e)
{
e.printStackTrace();
}
BitmapDrawable bitmapDrawable = (BitmapDrawable) image
.getDrawable();
if (bitmapDrawable != null
&& !bitmapDrawable.getBitmap().isRecycled()) // ①
{
bitmapDrawable.getBitmap().recycle();
}
// 改变ImageView显示的图片
image.setImageBitmap(BitmapFactory
.decodeStream(assetFile)); // ②
}
});
}
}
结果Gif
二、绘图
在为我们的应用界面添砖加瓦的过程中,除了可以使用已有的图片外,Android应用还经常需要在运行过程中动态的生成图片,而这样就需要借助于Android的绘图支持了。
(1)绘图基础——Canvas、Paint
Android的绘图与Swing中的绘图思路类似即开发一个自定义类,然后让该类继承JPanel,之后重写其中的paint(Graphics g)方法即可。而我们An