Android Su易做图ceView 详解(三)
Su易做图ceView 示波器的例子:直接上代码了就
该程序会根据单击的按钮在屏幕上自动绘制正弦波和余弦波形。程序每次绘制时只需要绘制(更新)当前点的波形,前面已经绘制的波形无须更新,利用了Su易做图ceHolder的lockCanvas(Rect r)方法
1.布局文件Layout/show_wave.xml:
[html]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation ="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/sin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="正弦曲线"
/>
<Button
android:id="@+id/cos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="余弦曲线"
/>
<Su易做图ceView
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
2.主界面Activity:ShowWave
[java]
package com.infy.configuration;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.Su易做图ceHolder;
import android.view.Su易做图ceView;
import android.view.View;
import android.view.Su易做图ceHolder.Callback;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ShowWave extends Activity{
private Su易做图ceHolder holder;
private Paint paint;
final int HEIGHT=320;
final int WIDTH=320;
final int X_OFFSET = 5;
private int cx = X_OFFSET;
//实际的Y轴的位置
int centerY = HEIGHT /2;
Timer timer = new Timer();
TimerTask task = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.show_wave);
final Su易做图ceView su易做图ce = (Su易做图ceView)findViewById(R.id.show);
//初始化Su易做图ceHolder对象 www.zzzyk.com
holder = su易做图ce.getHolder();
paint = new Paint();
paint.setColor(Color.GREEN);
paint.setStrokeWidth(3);
Button sin =(Button)findViewById(R.id.sin);
Button cos =(Button)findViewById(R.id.cos);
OnClickListener listener = (new OnClickListener() {
@Override
public void onClick(final View source) {
// TODO Auto-generated method stub
drawBack(holder);
cx = X_OFFSET;
if(task != null){
task.cancel();
}
task = new TimerTask() {
@Override
public void run() {
int cy = source.getId() == R.id.sin ? centerY -(int)(100 * Math.sin((cx -5) *2 * Math.PI/150)):
centerY -(int)(100 * Math.cos((cx-5)*2*Math.PI/150));
Canvas canvas = holder.lockCanvas(new Rect(cx,cy-2,cx+2,cy+2));
canvas.drawPoint(cx, cy, paint);
cx++;
if(cx >WIDTH){
task.cancel();
task = null;
}
补充:移动开发 , Android ,