现在的位置: 首页 > 综合 > 正文

android 绘图、自定义组件

2013年01月24日 ⁄ 综合 ⁄ 共 2532字 ⁄ 字号 评论关闭

我们在开发当中很多时候都需要自定义组件,通过自定义组件,可以随心所欲定制酷炫的效果。下面将演示自定义绘图组件。我们要绘制一个红色的线条。

1.建立工程文件,名为TouchDemo。




2.布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<org.touch.cn.MyPaintView 
android:id="@+id/myView"
   android:layout_width="fill_parent" 
   android:layout_height="fill_parent" />
</LinearLayout>

3.核心代码

MainActivity.java如下:


package org.touch.cn;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    } 
}


MyPaintView.java如下:

package org.touch.cn;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.ListActivity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyPaintView  extends View{
private List<Point> allpoint = new ArrayList<Point>();//保存所以的操作坐标
public MyPaintView(Context context, AttributeSet attrs) {//接收context,同时接收属性集合。
super(context, attrs);//调用父类的构造
super.setOnTouchListener(new OnTouchListenerimpl());
}
private class OnTouchListenerimpl implements OnTouchListener{

@Override
public boolean onTouch(View v, MotionEvent event) {
Point p = new Point((int)event.getX(),(int)event.getY());//将坐标保存在Point类
if(event.getAction()==MotionEvent.ACTION_DOWN){ //用户按下
MyPaintView.this.allpoint=new ArrayList<Point>();//重绘
MyPaintView.this.allpoint.add(p);//保存坐标点

}else if(event.getAction()==MotionEvent.ACTION_MOVE){//用户移动
MyPaintView.this.allpoint.add(p);//记录坐标点
MyPaintView.this.postInvalidate();//重绘图形
}else if(event.getAction()==MotionEvent.ACTION_UP){//用户松开
MyPaintView.this.allpoint.add(p);//记录坐标点
MyPaintView.this.postInvalidate();//重绘图形


}

return true; //表示下面的操作不在执行了。
}

}
@Override
protected void onDraw(Canvas canvas) { //进行绘图
Paint paint = new Paint();//依靠此类开始画线
paint.setColor(Color.RED);
if(MyPaintView.this.allpoint.size()>0)//有坐标点保存的时候开始进行绘图
{
Iterator<Point> iterator = MyPaintView.this.allpoint.iterator();
Point first=null;
Point last=null;
while(iterator.hasNext()){
if(first==null)
{
first= (Point)iterator.next();//取出坐标
}else {
if(last!=null){//前一阶段已经完成
first = last;//重新开始下一阶段
}
last=(Point)iterator.next();//结果点坐标
canvas.drawLine(first.x, first.y, last.x, last.y, paint);
}
}
}
}

}


4.运行效果



5。奉上源码:  ===========》http://download.csdn.net/detail/gsg8709/4144454



抱歉!评论已关闭.