如何将Paint或Color传递给使用活动中的onDraw()方法的新对象?

时间:2014-02-28 13:46:12

标签: 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 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;
    }

}

1 个答案:

答案 0 :(得分:2)

您已在构造函数中使用color覆盖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);


}