Hi, I am trying to get my canvas update application from a custom view I made. This view creates a square with lines and a circle in the center. I want to click a button and draw random x and y coordinates on 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 donβt understand how to refer to the canvas from my user view and change it or redraw it. Im assuming you are using invalidate (); but I am puzzled by how this method works, can someone help me?
source share