I'm trying to create some pixels with a random color by passing the color into the constructor as I'm creating the object. I can't seem to do it no matter what I try.
Here is my code..
Object to be drawn
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);
}
}
My MainActivity
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;
}
}
You are already overriding your color
with new Paint()
in the constructor. Then when you call color.set(Color)
you are not changing it.
I suggest you pass the color as int
in the constructor and then use setColor
public Particle(Context context, int locationX, int locationY, int sizeX, int sizeY, int paintColor) {
(...)
color = new Paint();
color.setColor(paintColor);
}
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.