如何使用DrawRect方法在画布上绘制一组矩形?我试图通过传递块的坐标来生成动态室内地图。
我想知道..如何在for循环中使用drawRect方法..!
我在Luke Taylor的帮助下完成了两门课程。(谢谢..!:))
一个是坐标,另一个是名为DrawMapActivity的主类。 现在我需要知道如何填充坐标数组???
打包itgsm.drawmap;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
public class DrawMapActivity extends Activity {
/** Called when the activity is first created. */
static Coordinates[] coordinates = new Coordinates[10]; // 10 is just an example
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
//
// }
public void onDraw(Canvas canvas) {
Paint myPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
myPaint.setStrokeWidth(8/*1 /getResources().getDisplayMetrics().density*/);
myPaint.setColor(0xffff0000); //color.RED
for(int i = 0; i < coordinates.length; i++) {
canvas.drawRect(new Rect(coordinates[i].getX(), coordinates[i].getY(), coordinates[i].getX() + 10,coordinates[i].getY() + 10), myPaint); // 10 is the dimension of your block
}
}
}
答案 0 :(得分:2)
您可以创建一个方法,该方法接受包含坐标的对象数组:
这将是包含坐标的名为“Coordinate”的类。
public class Coordinate {
int x;
int y;
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
您可以创建包含各个坐标的这些对象的数组:
Coordinates[] coordinates = new Coordinates[10]; // 10 is just an example
在渲染方法中,您现在可以渲染各个块。
public void drawMap(Coordinates[] coordinates) {
for(int i = 0; i < coordinates.length; i++) {
canvas.drawRect(new Rect(coordinates[i].getX, coordinates[i].getY, coordinates[i].getX + 10,coordinates[i].getY + 10), paint); // 10 is the dimension of your block
}
}
我希望这会有所帮助。
<强>更新强>
这是使用Coordinate对象填充数组的一个索引的方法:
coordinates[1] = new Coordinate();
coordinates[1].setX(0);
coordinates[1].setY(0);
答案 1 :(得分:0)
public class DrawDemo extends Activity {
DemoView demoview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
demoview = new DemoView(this);
setContentView(demoview);
}
private class DemoView extends View{
public DemoView(Context context){
super(context);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// custom drawing code here
// remember: y increases from top to bottom
// x increases from left to right
int x = 0;
int y = 0;
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
// make the entire canvas white
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// another way to do this is to use:
// canvas.drawColor(Color.WHITE);
// draw a solid green rectangle
paint.setAntiAlias(false);
paint.setColor(Color.GREEN);
for(int i=0;i<10;i++)
{
//make changes in arguments here
canvas.drawRect(100, 5, 200, 30, paint);
}
}
}
}