画笔、画布详细简介:
https://github.com/GcsSloop/AndroidNote/blob/master/CustomView/Advance/%5B03%5DCanvas_Convert.md
效果图:
新建一个类继承View
源码如下:
public class Table extends View { private Paint mPaint ; // 1.创建一个画笔 private int lastX = 0;//记录上次X轴移动的位置 private int lastY = 0;//记录上次Y轴移动的位置 private int screenWidth;//屏幕宽度 private int screenHeight;//屏幕高度 /** * 获取屏幕宽高 */ public void screen(){ DisplayMetrics dm = getResources().getDisplayMetrics(); screenWidth=dm.widthPixels; screenHeight = dm.heightPixels; } public Table(Context context) { super(context); init(); screen(); } /** * 初始化 */ private void init() { mPaint = new Paint(); mPaint.setColor(Color.BLACK); //设置画笔颜色 mPaint.setStyle(Paint.Style.FILL); //设置画笔模式为填充 mPaint.setStrokeWidth(5f); //设置画笔宽度为5px } public Table(Context context, AttributeSet attrs) { super(context, attrs); } public Table(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * 移动事件的处理 * @param event * @return */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN://手指按下,获取当前的X,Y lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); break; case MotionEvent.ACTION_MOVE://手指移动,计算移动单位,重新绘制当前控件 int dx =(int)event.getRawX() - lastX; int dy =(int)event.getRawY() - lastY; int left = getLeft() + dx; int top = getTop() + dy; int right = getRight() + dx; int bottom = getBottom() + dy; if(left < 0){ left = 0; right = left + getWidth(); } if(right > screenWidth){ right = screenWidth; left = right - getWidth(); } if(top < 0){ top = 0; bottom = top + getHeight(); } if(bottom > screenHeight){ bottom = screenHeight; top = bottom - getHeight(); } layout(left, top, right, bottom); lastX = (int) event.getRawX(); lastY = (int) event.getRawY(); break; case MotionEvent.ACTION_UP://手指抬起 break; } return true; } /** * 计算控件大小 * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //设置自定义控件的大小 setMeasuredDimension(600,600); } /** * 描绘方法 * @param canvas */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawColor(Color.WHITE); //绘制背景颜色 canvas.drawLines(new float[]{ // 绘制一组线 每四数字(两个点的坐标)确定一条线 0,0,600,0, 0,200,600,200, 0,400,600,400, 0,600,600,600, 0,0,0,600, 200,0,200,600, 400,0,400,600, 600,0,600,600, },mPaint); } }
在类中添加子控件即可!
public class MainActivity extends Activity { RelativeLayout activity_main; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } /** * 初始化视图 */ private void initView() { activity_main=(RelativeLayout)findViewById(R.id.activity_main); activity_main.addView(new Table(MainActivity.this));//添加子控件 } }