1.自定义view
2.重写onDraw()方法
3.XML中引用
自定义view代码:
public class MyView02 extends View{ private Bitmap bitmap;//本地图片资源 private Paint paint;//画笔 public MyView02(Context context, AttributeSet attrs) { super(context, attrs); initBtimap(); } /** * 初始化图片 */ private void initBtimap() { paint = new Paint();//创建一个画笔 bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.h_p_l_image); } /** * 重写绘制方法 */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setAntiAlias(true);//打开抗锯齿 paint.setColor(Color.RED);//设置画笔颜色 paint.setTextSize(15);//设置画笔字体大小 canvas.drawBitmap(bitmap, 10, 10, paint);//绘制图片 canvas.save();//保存画布状态 Matrix m1 = new Matrix();//创建矩阵对象 m1.setTranslate(500, 10);//平移矩阵 Matrix m2 = new Matrix();//创建矩阵对象 m2.setRotate(15);//以一定的角度旋转矩阵 Matrix m3 = new Matrix();//创建矩阵对象 m3.setConcat(m1, m2);//连接矩阵1和矩阵2 m3.setScale(0.8f, 0.8f);//缩放矩阵 canvas.drawBitmap(bitmap, m2, paint); canvas.restore();//恢复画布状态 canvas.save();//保存画面状态 paint.setAlpha(180);//设置透明度 m1.setTranslate(200, 100);//平移矩阵1 m2.setScale(1.3f, 1.3f);//缩放矩阵2 m3.setConcat(m1, m2);//连接矩阵1和矩阵2 canvas.drawBitmap(bitmap, m3, paint);//绘制图片 paint.reset();//恢复画笔设置 canvas.restore();//恢复画布设置 paint.setTextSize(40);//设置字体大小 paint.setColor(Color.RED);//设置画笔颜色 canvas.drawText("图片的宽度" + bitmap.getWidth(), 20, 220, paint); paint.reset(); paint.setTextSize(30); paint.setColor(Color.BLACK); canvas.drawText("图片的高度" + bitmap.getHeight(), 20, 260,paint); paint.reset();//恢复画笔设置 } }XML中引用:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".ui.activity.MyViewActivity"> <testku.mygame.ui.myview.MyView02 android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>运行效果: