創建一個自定義的視圖類, MyCanvas.java
package com.AndroidCanvasDraw;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
public class MyCanvas extends View {
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
int canvasVerticalCenter;
public MyCanvas(Context context) {
super(context);
// TODO Auto-generated constructor stub
init();
}
public MyCanvas(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
init();
}
public MyCanvas(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
init();
}
private void init(){
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(1);
paint.setColor(Color.WHITE);
}
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
prepareProject();
for(int i = 0; i < getWidth(); i++){
int value = (int)(Math.sin(Math.toRadians(i))*100);
project(i, value, canvas);
}
}
void prepareProject(){
canvasVerticalCenter = getHeight()/2;
}
void project(int x, int y, Canvas c){
c.drawLine(x, canvasVerticalCenter, x, canvasVerticalCenter-y, paint);
//c.drawPoint(x, canvasVerticalCenter-y, paint);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// TODO Auto-generated method stub
setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),
MeasureSpec.getSize(heightMeasureSpec));
}
}
在主代碼調用使用 MyCanvas 類.
package com.AndroidCanvasDraw;
import android.app.Activity;
import android.os.Bundle;
public class AndroidCanvasDraw extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyCanvas myCanvas = new MyCanvas(this);
setContentView(myCanvas);
}
}
相關文章:
- 自由落體方程式
沒有留言:
發佈留言