public class MyView3 extends View implements View.OnClickListener{ private Paint paint; private int width; private int height; private int centerX; private int centerY; private RectF rectF; private Paint pain; private int[] colors; private int jieshu; public MyView3(Context context) { this(context,null); } public MyView3(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public MyView3(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initView(); } private void initView() { setOnClickListener(this); paint = new Paint(); paint.setColor(Color.RED); rectF = new RectF(-200, -200, 200, 200); pain = new Paint(); pain.setColor(Color.GRAY); //定义颜色 colors = new int[]{Color.GREEN, Color.BLUE, Color.YELLOW,Color.CYAN}; jieshu=360/colors.length; } //测量 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //测量实际的高度和宽度 width = getMeasuredWidth(); height=getMeasuredHeight(); //放在屏幕的中间 centerX=width/2; centerY=height/2; } //画笔 @SuppressLint("DrawAllocation") @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.translate(centerX,centerY); //矩形 浮点型比整型更精确 canvas.drawRect(rectF,paint); //圆形 //canvas.drawCircle(0,0,200,pain); //旋转 canvas.rotate(d); //弧形 huxing(canvas); } //用弧形 进行循环 画出一个圆 private void huxing(Canvas canvas) { int qishi=0; for (int i=0;i<colors.length;i++ ){ pain.setColor(colors[i]); canvas.drawArc(rectF,qishi,jieshu,true,pain); qishi+=jieshu; } } //事件 @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: Log.e("==","ACTION_DOWN"); break; case MotionEvent.ACTION_UP: Log.e("==","ACTION_UP"); break; case MotionEvent.ACTION_MOVE: Log.e("==","ACTION_MOVE"); break; } return super.onTouchEvent(event); } //先让他旋转 60度 循环一次 +5 int d=60; @Override public void onClick(View v) { TimerTask timer = new TimerTask() { @Override public void run() { d+=5; //子线程中刷新 postInvalidate(); } }; Timer timer1 = new Timer(); timer1.schedule(timer,2000,50); }
自定义View-----点击小球转动
最新推荐文章于 2019-04-08 00:05:35 发布