一.使用ImageView绘制图片
1.在布局文件中添加ImageView控件
<ImageView
android:id="@+id/imageView"
android:layout_width="120dp"
android:layout_height="120dp"
/>
2.在Activity中找到控件并设置图片
imageView= findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.girl);
二.使用SurfaceView绘制图片
1.在布局文件中添加CustomSurfaceView控件
<com.ry.question1.CustomSurfaceView
android:layout_width="120dp"
android:layout_height="120dp"
/>
2.主要代码
private void initView() {
mHolder=getHolder();
mHolder.addCallback(this);
setFocusable(true);
setFocusableInTouchMode(true);
this.setKeepScreenOn(true);
}
public CustomSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
@Override
public void surfaceCreated(@NonNull SurfaceHolder holder) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.girl);
Bitmap bitmap = bd.getBitmap();
Canvas canvas = holder.lockCanvas(); // 先锁定当前surfaceView的画布
canvas.drawBitmap(bitmap, 0, 0, paint); //执行绘制操作
holder.unlockCanvasAndPost(canvas); // 解除锁定并显示在界面上
}
三.使用自定义view绘制图片
1.布局
<com.ry.question1.CustomView
android:layout_width="120dp"
android:layout_height="120dp"/>
2.主要代码
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.girl);
Bitmap bitmap = bd.getBitmap();
// 方式二:
// Bitmap bitmap = BitmapFactory.decodeFile("/storage/emulated/0/wuqian.jpg"); // 获取bitmap
canvas.drawBitmap(bitmap, 0, 0, paint); //执行绘制操作
super.onDraw(canvas);
}
四.显示效果