我正在做一个测试应用程序,以便将来开发一个更复杂的应用程序,我问自己是否可以在 Canvas 上绘制更多矩形(也许一个左,一个中心,一个右)。不使用任何ImageView、TextView或者这个东西。 这是我的代码:
public class MioCanvas extends View {
Paint paint;
Rect rect;
public MioCanvas(Context context) {
super(context);
paint = new Paint();
rect = new Rect();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.GRAY);
paint.setStrokeWidth(3);
canvas.drawRect(0, 1999999, canvas.getWidth() / 2, canvas.getHeight() / 2, paint);
}
}
这是 Activity :
public class MainActivity extends AppCompatActivity {
MioCanvas mioCanvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mioCanvas = new MioCanvas(this);
mioCanvas.setBackgroundColor(Color.GREEN);
setContentView(mioCanvas);
}
}
最佳答案
要实现您想要的效果,例如,您可以创建一个名为 MyRectangle 的对象,并在其中保留对其宽度、高度、positionX、positionY、颜色引用等的引用。
在您的 MioCanvas
类中放置一个全局变量,例如:
List<MyRectangle> rectangleList;
在构造函数中初始化它,创建一些矩形并将它们添加到列表中。
最后遍历 onDraw
方法内的列表来绘制矩形:
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for(MyRectangle rectangle : rectangleList){
paint.setColor(rectangle.getColour());
paint.setStrokeWidth(rectangle.getStroke());
canvas.drawRect(rectangle.getPositionX(), rectangle.getPositionY(), rectangle.getWidth() / 2, rectangle.getHeight() / 2, paint);
}
}
关于java - 如何在 Canvas 上以原始方式绘制更多矩形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55610738/