在Android Studio中,可以根据用户输入的条件显示可绘制的图形。以下是一种实现方法:
以下是一个简单的示例代码:
public class MyView extends View {
private int shapeType; // 用户输入的条件,用于确定要绘制的图形类型
public MyView(Context context) {
super(context);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 根据用户输入的条件绘制相应的图形
switch (shapeType) {
case 1:
drawRectangle(canvas);
break;
case 2:
drawCircle(canvas);
break;
case 3:
drawLine(canvas);
break;
// 可以根据需要添加更多的条件和对应的图形绘制方法
}
}
private void drawRectangle(Canvas canvas) {
// 绘制矩形
Rect rect = new Rect(100, 100, 300, 300);
Paint paint = new Paint();
paint.setColor(Color.RED);
canvas.drawRect(rect, paint);
}
private void drawCircle(Canvas canvas) {
// 绘制圆形
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int radius = 200;
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawCircle(centerX, centerY, radius, paint);
}
private void drawLine(Canvas canvas) {
// 绘制线条
Paint paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
canvas.drawLine(100, 100, 300, 300, paint);
}
public void setShapeType(int shapeType) {
this.shapeType = shapeType;
invalidate(); // 通知View组件重绘
}
}
在Activity中使用该自定义View组件:
public class MainActivity extends AppCompatActivity {
private EditText inputEditText;
private Button drawButton;
private MyView myView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inputEditText = findViewById(R.id.inputEditText);
drawButton = findViewById(R.id.drawButton);
myView = findViewById(R.id.myView);
drawButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = inputEditText.getText().toString();
int shapeType = Integer.parseInt(input);
myView.setShapeType(shapeType);
}
});
}
}
在上述示例中,用户可以通过输入框输入条件,然后点击按钮来显示相应的图形。根据用户输入的条件,调用MyView的setShapeType()方法来设置要绘制的图形类型,并触发View的重绘。在View的onDraw()方法中根据图形类型调用相应的绘制方法来绘制图形。
注意:以上示例仅为演示目的,实际应用中可能需要根据具体需求进行修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云