📅  最后修改于: 2020-10-11 03:58:56             🧑  作者: Mango
android.graphics.Canvas可用于在android中绘制图形。它提供了绘制椭圆,矩形,图片,文本,线条等的方法。
android.graphics.Paint类与画布一起使用以绘制对象。它包含颜色和样式的信息。
在此示例中,我们将在android中显示2D图形。
package com.example.simplegraphics;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class MainActivity 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
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
// make the entire canvas white
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
// draw blue circle with anti aliasing turned off
paint.setAntiAlias(false);
paint.setColor(Color.BLUE);
canvas.drawCircle(20, 20, 15, paint);
// draw green circle with anti aliasing turned on
paint.setAntiAlias(true);
paint.setColor(Color.GREEN);
canvas.drawCircle(60, 20, 15, paint);
// draw red rectangle with anti aliasing turned off
paint.setAntiAlias(false);
paint.setColor(Color.RED);
canvas.drawRect(100, 5, 200, 30, paint);
// draw the rotated text
canvas.rotate(-45);
paint.setStyle(Paint.Style.FILL);
canvas.drawText("Graphics Rotation", 40, 180, paint);
//undo the rotate
canvas.restore();
}
}
@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;
}
}