【问题标题】:Android setBackgroundColor doesn't give any resultAndroid setBackgroundColor 没有给出任何结果
【发布时间】:2015-04-26 13:10:03
【问题描述】:

在我的应用程序中,我想得到这样的东西。

这是代码

public class Tunnel extends View {
    Paint paint = new Paint();
    Toast toast;

    public Tunnel(Context context) {
        super(context);

        setBackgroundColor(Color.BLACK);
        paint.setColor(Color.WHITE);

        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (toast != null) {
                    toast.cancel();
                }
                int x = (int) event.getX();
                int y = (int) event.getY();

                if (y > myFunction(x) + 100 || y < myFunction(x)) {
                    toast = Toast.makeText(getContext(), "Out of bounds", Toast.LENGTH_SHORT);
                } else {
                    toast = Toast.makeText(getContext(), "Perfect", Toast.LENGTH_SHORT);
                }
                toast.show();
                return false;
            }
        });
    }

    @Override
    public void onDraw(Canvas canvas) {
        for (int x = 0; x < canvas.getWidth(); x++) {
            //upper bound
            canvas.drawPoint(x, (float) myFunction(x), paint);

            //lower bound
            canvas.drawPoint(x, (float) myFunction(x) + 100, paint);

            canvas.drawLine(x, (float) myFunction(x), x, (float) myFunction(x) + 100, paint);
        }
    }

    private double myFunction(double x) {
        return 50 * Math.sin(x / 50) + 400;
    }
}

但不是这样,我得到的是一个白屏。 onDraw 方法工作正常,我已经用红色对其进行了测试,但为什么 setBackgroundColor 不起作用?我做错了什么?

【问题讨论】:

    标签: android


    【解决方案1】:

    好的,我发现了问题。我需要移动线路

    setBackgroundColor(Color.BLACK);

    进入onDraw 方法,所以我的它看起来像这样

     @Override
        public void onDraw(Canvas canvas) {
            for (int x = 0; x < canvas.getWidth(); x++) {
                //upper bound
                canvas.drawPoint(x, (float) myFunction(x), paint);
    
                //lower bound
                canvas.drawPoint(x, (float) myFunction(x) + 100, paint);
    
                canvas.drawLine(x, (float) myFunction(x), x, (float) myFunction(x) + 100, paint);
            }
            setBackgroundColor(Color.BLACK);
        }
    

    【讨论】:

      猜你喜欢
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-24
      相关资源
      最近更新 更多