Jaqen's Blog

使用三种不同的方式绘制图片

字数统计: 292阅读时长: 1 min
2019/07/05 Share

在 Android 平台上绘制一张图片,使用三种不同的 API,ImageView、SurfaceView、自定义 View。

ImageView 绘制图片

这种方式较为普遍简单。

1
2
3
ImageView imageView = findViewById(R.id.image_view);
Bitmap bitmap = Util.getBitmapFromAssetsFile(this, "Jaqen.png");
imageView.setImageBitmap(bitmap);

SurfaceView 绘制图片

SurfaceView 是 View 的一个子类,特点在于其实现了双缓冲技术,适用于频繁刷新页面的场景。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
SurfaceView surfaceView = findViewById(R.id.surface_view);
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
return;
}

Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
Bitmap bitmap = Util.getBitmapFromAssetsFile(SurfaceViewActivity.this, "Jaqen.png");
Canvas canvas = holder.lockCanvas();
canvas.drawBitmap(bitmap, 0, 0, paint);
holder.unlockCanvasAndPost(canvas);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {

}
});

自定义 View 绘制图片

还可以通过自定义 View 绘制图片。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class CustomView extends View {

private Paint mPaint;
private Bitmap mBitmap;

public CustomView(Context context) {
this(context, null);
}

public CustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.STROKE);
mBitmap = Util.getBitmapFromAssetsFile(context, "Jaqen.png");
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBitmap != null) {
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
}
}
}

源码

https://github.com/zywudev/AndroidMultiMediaLearning

CATALOG
  1. 1. ImageView 绘制图片
  2. 2. SurfaceView 绘制图片
  3. 3. 自定义 View 绘制图片
  4. 4. 源码