简体   繁体   中英

how to draw rectangle canvas?

In this example code I give a nice square in the form I want. canvas.drawRect (100, 300, 600, 800, paint); values work. But what I want is to call these values from the Activity class. So I want to send these values to the Draw class in the activity class. How can I do that ? For example, I want to send an activity class as drawRect (100,100,100,100, Color.BLUE). I do not want to write these values in the 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)

You need to make method and pass value from activity to draw class:-

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

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);
 }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM