在这个示例代码中,我以我想要的形式给出一个漂亮的正方形。 canvas.drawRect(100,300,600,800,paint);价值观工作。但我想要的是从Activity类中调用这些值。所以我想将这些值发送到activity类中的Draw类。我怎样才能做到这一点 ?例如,我想将一个活动类作为drawRect(100,100,100,100,Color.BLUE)发送。我不想在Draw类中写这些值。
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);
答案 0 :(得分:0)
您可以为边界创建局部变量,并在将该视图添加到视图组之前使用setter或init函数设置它们。(在您的情况下为constraintLayout.addView(draw)
答案 1 :(得分:0)
您需要创建方法并将值从活动传递到绘制类: -
Draw draw = new Draw(this,100, 300, 600, 800);
constraintLayout.addView(draw);
绘制课程
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);
}
}