Hi im trying to get my app to update a canvas from a custom view i made This view creates a square with lines and a circle in the center. I want to press a button and draw random x and y coordinates to the canvas.
Heres My MainActivity:
@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
}
Heres My Custom View:
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;
}
I dont get how to reference the canvas from my Custom View and change or redraw it. Im assuming you use invalidate(); but im puzzled on how this method works can any1 help me out?
When invalidate
is called onDraw
is called again, you should also use this.getHolder().addCallback(this);
and let your class implement Callback
and add the unimplemented methods
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With