package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends AppCompatActivity {
final static int LINE = 1, RECT = 2, CIRCLE = 3;
static int kindofshape = LINE;
private static class MyGraphicView extends View {
int startX, startY, endX, endY;
public MyGraphicView(Context myContext) {
super(myContext);
}
@Override
public boolean onTouchEvent(MotionEvent myEvent) {
switch (myEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int)myEvent.getX();
startY = (int)myEvent.getY();
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
endX = (int)myEvent.getX();
endY = (int)myEvent.getY();
this.invalidate();
break;
}
return true;
}
protected void onDraw(Canvas myCanvas) {
super.onDraw(myCanvas);
Paint myPaint = new Paint();
myPaint.setAntiAlias(true);
myPaint.setStrokeWidth(8);
myPaint.setStyle(Paint.Style.STROKE);
myPaint.setColor(Color.RED);
switch (kindofshape) {
case LINE:
myCanvas.drawLine(startX, startY, endX, endY, myPaint);
break;
case RECT:
myCanvas.drawRect(startX, startY, endX, endY, myPaint);
break;
case CIRCLE:
int radius = (int)Math.sqrt(Math.pow((endX - startX), 2.0) + Math.pow((endY - startY), 2.0));
myCanvas.drawCircle(startX, startY, radius, myPaint);
break;
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyGraphicView(this));
}
public boolean onCreateOptionsMenu(Menu myMenu) {
super.onCreateOptionsMenu(myMenu);
myMenu.add(0, 1, 0, "LINE");
myMenu.add(0, 2, 0, "RECT");
myMenu.add(0, 3, 0, "CIRCLE");
return true;
}
public boolean onOptionsItemSelected(MenuItem myItem) {
switch (myItem.getItemId()) {
case 1:
kindofshape = LINE;
return true;
case 2:
kindofshape = RECT;
return true;
case 3:
kindofshape = CIRCLE;
return true;
}
return super.onOptionsItemSelected(myItem);
}
}