zoukankan      html  css  js  c++  java
  • 自定义View

    * 继承View,重写画布和画笔

    /**
     * Created by Administrator on 2016/4/21.
     * 1:画笔
     * 2:画布
     */
    public class MyView extends View {
        private Paint paint;//画笔
        //用java代码直接创建时调用
        public MyView(Context context) {
            super(context);
            init();
        }
        //在xml文件中使用,会调用这个构造方法。AttributeSet;表示布局中设置的属性集合。
        public MyView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        private void init() {
            //初始化工作。
            paint = new Paint();
            //设置画笔的一些属性。
            paint.setColor(Color.parseColor("#ff0000"));//设置颜色
            paint.setAntiAlias(true);//去掉锯齿
            paint.setStyle(Paint.Style.FILL);//设置样式:填充还是描边等等。
        }
        /*
        自定义view  执行方法的流程
        1;先要计算自己的大小。  ------onMeasure
        2:需要在父容器里面去定位。------onLayout
        3:开始描绘。------onDraw
         */
        //测量自己的大小
        /*
        MeasureSpec ---包含大小和模式的对象
        widthMeasureSpec ---包含宽度的大小和模式
        heightMeasureSpec ---包含高度的大小和模式
         */
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            Log.i("View","onMeasure");
        }
        //定位。一般的情况下,如果是view,一般都不会重写这个方法。ViewGroup就会重写这个方法。
        @Override
        protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
            super.onLayout(changed, left, top, right, bottom);
            Log.i("View", "onLayout");
        }
        //描画内容
        //Canvas----画布
        private int x,y;
        @Override
        protected void onDraw(Canvas canvas) {
           //画东西。
            canvas.drawCircle(x,y,40,paint);
            canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher),40,60,paint);
            canvas.drawText("我很好",100,100,paint);
    
        }
    
        //按钮按下重绘画布
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            if(event.getAction()==MotionEvent.ACTION_DOWN){
                x = (int) event.getX();
                y = (int) event.getY();
                invalidate();
            }
            return super.onTouchEvent(event);
        }
    }

     

  • 相关阅读:
    搭建yum服务器
    linux 网卡
    yum安装包另存
    CentOS下VMware用桥接模式,静态ip上外网
    linux挂载硬盘以及卸载硬盘
    Word2010如何编辑好了直接发布csdn博文?
    【更新】用word文档来发布到csdn等博客上边免去一张张上传图片的烦恼
    在word上写博客直接发到CSDN
    word上传博客教程
    Word写博客-使用Word2013发布博文到博客园
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/5416929.html
Copyright © 2011-2022 走看看