球球



public class MyView extends View {


    private int weight;
    private int height;
    private Paint mPaint;
    private int speedX = 50,speedY = 20;
    private int x = 200, y = 200;


    public MyView(Context context) {
        super(context);
    }


    public MyView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }


    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


        initPaint();
    }


    private void initPaint() {
        //画笔
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setStrokeWidth(10);
        //抗锯齿
        mPaint.setAntiAlias(true);
        //设置空心
        mPaint.setStyle(Paint.Style.FILL);


    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }


    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }


    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        weight = w;
        height = h;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);


        canvas.drawCircle(x,y,50,mPaint);


        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        invalidate();
    }


    @Override
    public void invalidate() {
        super.invalidate();
        x += speedX;
        y += speedY;


        if(x <= 50 || x >= getWidth()){
            speedX *= -1;
        }else if (y <=0 || y >= getHeight()){
            speedY *= -1;
        }






    }
}

猜你喜欢

转载自blog.csdn.net/qq_41637459/article/details/80644542
今日推荐