Java 如何将油漆或颜色传递给正在使用活动中的onDraw()方法的新对象?
在创建对象时,我试图通过将颜色传递到构造函数来创建一些具有随机颜色的像素。不管我怎么努力,我似乎都做不到 这是我的密码 要绘制的对象Java 如何将油漆或颜色传递给正在使用活动中的onDraw()方法的新对象?,java,android,canvas,Java,Android,Canvas,在创建对象时,我试图通过将颜色传递到构造函数来创建一些具有随机颜色的像素。不管我怎么努力,我似乎都做不到 这是我的密码 要绘制的对象 public class Particle extends View{ private int locationX; private int locationY; private int sizeX; private int sizeY; private Paint color; private Rect rect
public class Particle extends View{
private int locationX;
private int locationY;
private int sizeX;
private int sizeY;
private Paint color;
private Rect rect;
public Particle(Context context, int locationX, int locationY, int sizeX, int sizeY, Paint color) {
super(context);
// TODO Auto-generated constructor stub
this.locationX = locationX;
this.locationY = locationY;
this.sizeX = sizeX;
this.sizeY = sizeY;
this.color = color;
rect = new Rect();
color = new Paint();
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
rect.set(0,0, sizeX, sizeY);
color.setStyle(Paint.Style.FILL);
//this is where it fails, the color defaults to black.
//will not take color = new Paint(Color.RED); from MainActivity
//as parameter.
color.set(color);
canvas.drawRect(rect, color);
}
}
我的主要活动
public class MainActivity extends Activity {
private Particle particle;
private Paint color;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
color = new Paint(Color.RED);
particle = new Particle(this, 0, 0, 450, 120, color);
setContentView(particle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
您已经在构造函数中使用
new Paint()
覆盖了颜色。然后,当您调用color.set(color)
时,您不会更改它
我建议您在构造函数中将颜色传递为int
,然后使用setColor
public Particle(Context context, int locationX, int locationY, int sizeX, int sizeY, int paintColor) {
(...)
color = new Paint();
color.setColor(paintColor);
}
别担心,这会发生在我们所有人身上。很高兴我能帮忙