2011-11-22 128 views
0

我有一个简单的程序,可以通过画布绘制简单的形状。android:随机选择属性的方法

private class MyViewCircle extends View { 

    public MyViewCircle(Context context) { 
     super(context); 
     // TODO Auto-generated constructor stub 
    } 

    @Override 
    protected void onDraw(Canvas canvas) { 
     // TODO Auto-generated method stub 
     super.onDraw(canvas); 
     Paint paint = new Paint(); 
     paint.setAntiAlias(true); 
     paint.setColor(Color.RED); 
     canvas.drawCircle(89, 150, 30, paint); 
    } 

} 

正如你看到的,圆的属性是

(Color.RED); 
(89, 150, 30, paint); 

我想创建另一个类包括了很多其他功能(颜色和坐标),并选择他们随机。 那么,哪种方式更好,阵列或阵列列表还是别的?有人能给我一个例子怎么做?那么如何随机挑选它们并将它们放入绘图函数?干杯!

回答

0

尝试创建一个简单的Java对象包含所有的属性,然后将它们添加到一个列表,然后选择一个项目随意:

class MyAttributes { 
    int color; 
    int x, y; 
    int radius; 

    public MyAttributes(int color, int x, int y, int radius) { 
     this.color = color; 
     this.x = x; 
     this.y = y; 
     this.radius = radius; 
    } 
} 

在您的视图类:

private List<MyAttributes> mAttributes; 
private Random mRandom; 

public MyViewCircle(Context context) { 
    mRandom = new Random(); 
    mAttributes = new ArrayList<MyAttributes>(); 

    mAttributes.add(new MyAttributes(Color.RED, 80, 70, 199)); 
    mAttributes.add(new MyAttributes(Color.BLUE, 50, 170, 88)); 
} 


@Override 
protected void onDraw(Canvas canvas) { 
    super.onDraw(canvas); 
    Paint paint = new Paint(); 
    paint.setAntiAlias(true); 

    int randomPosition = mRandom.nextInt(mAttributes.size()); 
    MyAttributes randomAttr = mAttributes.get(randomPosition); 

    paint.setColor(randomAttr.color); 
    canvas.drawCircle(randomAttr.x, randomAttr.y, randomAttr.radius, paint); 
} 
+0

小优化到你的代码;不要在“mRandom.nextInt(mAttributes.size());”中调用“.size()”;“在每次调用时,一旦添加了所有属性,就会存储该大小。 – C0deAttack

+0

辉煌,我会试试! – nich

0

通常在Android上,我始终致力于使用Array来表现性能。

要随机选择,可以使用Math.random()方法或util.Random对象。使用其中的任何一个可以生成索引值,并使用该索引从数组中读取数据。

应该很简单,所以我不会写任何代码,除非你真的需要这样。