Preface
If you want to get started with audio and video development step by step, you need to learn, organize, and accumulate step by step. This article is the first one accumulated in audio and video development. The corresponding content to be learned is:
To draw a picture on the Android platform, use at least 3 different APIs, ImageView, SurfaceView, and custom View.
1. ImageView draws pictures
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + File.separator + "11.jpg");
imageView.setImageBitmap(bitmap);
If the code is submitted, if you encounter 02-04 17:25:52.573 E/BitmapFactory( 4789): Unable to decode stream: java.io.FileNotFoundException: sdcard/22.jpg: open failed: EACCES (Permission denied) problem
Add android:requestLegacyExternalStorage="true" in the manifest file
2. SurfaceView draws pictures
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.surface);
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
return;
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
// 获取bitmap
Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath() + File.separator + "11.jpg");
// 先锁定当前surfaceView的画布
Canvas canvas = surfaceHolder.lockCanvas();
//执行绘制操作
canvas.drawBitmap(bitmap, 0, 0, paint);
// 解除锁定并显示在界面上
surfaceHolder.unlockCanvasAndPost(canvas);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
});
3. Customize View to draw pictures
public class CustomView extends View {
Paint paint = new Paint();
Bitmap bitmap;
public CustomView(Context context) {
super(context);
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
// 获取bitmap
bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getPath()
+ File.separator + "11.jpg");
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
// 不建议在onDraw做任何分配内存的操作
if (bitmap != null) {
canvas.drawBitmap(bitmap, 0, 0, paint);
}
}
}