如何绘制矩形canvas?

how to draw rectangle canvas?

在这个示例代码中,我以我想要的形式给出了一个漂亮的正方形。 canvas.drawRect (100, 300, 600, 800, 油漆);值工作。但我想要的是从 Activity class 中调用这些值。所以我想将这些值发送到 activity class 中的 Draw class。我怎样才能做到这一点 ?例如,我想发送一个 activity class 作为 drawRect (100,100,100,100, Color.BLUE)。我不想在 Draw class 中写入这些值。

Draw.java

public class Draw extends View {

Paint paint;
Path path;

public Draw(Context context) {
    super(context);
    init();
}

public Draw(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public Draw(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public void init(){
    paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(10);
    paint.setStyle(Paint.Style.STROKE);

}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    canvas.drawRect(100, 300, 600, 800, paint);
 }
 }

Activity.java

    constraintLayout=findViewById(R.id.constraint);
    Draw draw = new Draw(this);
    constraintLayout.addView(draw);

您可以为边界创建局部变量,并在将该视图添加到视图组之前使用 setter 或 init 函数设置它们。(constraintLayout.addView(draw) 在您的情况下

您需要创建方法并从 activity 传递值来绘制 class:-

Draw draw = new Draw(this,100, 300, 600, 800);
constraintLayout.addView(draw);

绘制class

public class Draw extends View {

Paint paint;
Path path;

float left; 
float top; 
float right; 
float bottom;

public Draw(Context context,float left, float top, float right, float bottom) {
    super(context);
    this.left = left;
    this.top = top;
    this.right = right;
    this.bottom = bottom;
    init();
}

public Draw(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public Draw(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public void init(){
    paint = new Paint();
    paint.setColor(Color.BLACK);
    paint.setStrokeWidth(10);
    paint.setStyle(Paint.Style.STROKE);
}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    canvas.drawRect(left, top, right, bottom, paint);
 }
 }