嗨,我试图让我的应用程序从我制作的自定义视图更新画布这个视图创建了一个正方形,中间有线条和圆圈。我想按下一个按钮并在画布上随机绘制 x 和 y 坐标。
这是我的主要活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// EditText numDart = (EditText) findViewById(R.id.numDarts);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public int convertToDpi(int px){
DisplayMetrics metrics = getResources().getDisplayMetrics();
int unit = metrics.widthPixels/20;
return px * unit;
}
public void drawCanvas(View v){
View view = (View) findViewById(R.id.canView);
Paint black = new Paint();
black.setColor(Color.BLACK);
black.setStyle(Style.FILL);
view.invalidate(); //dont know where to go from here
}
这是我的自定义视图:
public CanView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Rect myrect = new Rect();
myrect.set(-10, 10, 10, -10);
Paint blue = new Paint();
Paint white = new Paint();
white.setColor(Color.WHITE);
white.setStyle(Paint.Style.FILL);
Paint black = new Paint();
black.setColor(Color.BLACK);
black.setStyle(Paint.Style.FILL);
blue.setColor(Color.BLUE);
blue.setStyle(Paint.Style.FILL);
canvas.drawRect(myrect, blue);
canvas.drawCircle(convertToDpi(10), convertToDpi(10),convertToDpi(3), white);
canvas.drawLine(convertToDpi(10), 0, convertToDpi(10), convertToDpi(20), black);
canvas.drawLine(0, convertToDpi(10), convertToDpi(20), convertToDpi(10), black);
canvas.scale(5, 5, 0, 0);
}
@Override
public void postInvalidate() { //Logic for redrawig goes here???
// TODO Auto-generated method stub
super.postInvalidate();
}
public int convertToDpi(int px){
DisplayMetrics metrics = getResources().getDisplayMetrics();
int unit = metrics.widthPixels/20;
return px * unit;
}
我不知道如何从我的自定义视图中引用画布并更改或重绘它。我假设你使用 invalidate(); 但我对这种方法的工作原理感到困惑,any1 可以帮助我吗?