Android重绘式绘图

来源:互联网 发布:淘宝运营计划书模板 编辑:程序博客网 时间:2024/05/16 16:23

我一直都没有太搞明白Android到底是怎么绘图的,和绘图有关的概念实在太多了,我从来就没搞清楚过……

幸好,我也算是琢磨出了一套画图的解决方案吧,主要是利用view的onDraw函数来画的。

onDraw函数是一个回调函数,系统会在他觉得这个view需要重绘的时候调用这个函数,所以他画的图肯定是对的,不过他一重绘就是全部重绘,如果你每次只是额外添加东西的话,我总感觉不值…… 不像Windows GDI,你可以获取DC以后随便搞,安卓似乎不行,最保险的方法还是用onDraw。

怎么用onDraw呢?首先我们需要自己写一个类来继承ImageView类,当然继承View也可以……

public class SuperImageView extends ImageView{Paint paint;Bitmap bmp=BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.pic2);//如果要画文件里的图,需要先decodePointType touchPoint;PointType MAP_ORIGIN;List<PointType> toDraw;public SuperImageView(Context context) {super(context);// TODO Auto-generated constructor stub}public SuperImageView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);// TODO Auto-generated constructor stub}public SuperImageView(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stub}//以上都是构造函数,照抄即可,对我们没用public void setTouchPoint(PointType p){touchPoint = p;return;}public void setPointList(List<PointType> list){toDraw = list;return;}public void setMapOrigin(PointType origin){MAP_ORIGIN = origin;return;}//一般都是把信息设好,然后让他重画@Override//这里就是神奇的onDraw函数,已经给你提供canvas了,就在这儿随便怎么画都是对的,比如这里会把一个List里面所有的点画出来,以及如果TouchPoint不为空的话,也把TouchPoint画出来protected void onDraw(Canvas canvas){// TODO Auto-generated method stubsuper.onDraw(canvas);canvas.drawBitmap(bmp, 0, 0, null);Paint paint = new Paint(); paint.setColor(Color.BLUE);int i; for(i=0; i<toDraw.size();i++) { PointType now = toDraw.get(i); PointType tmp = new PointType(now.x, now.y); tmp = tmp.XYtoView(MAP_ORIGIN);canvas.drawCircle((float)tmp.x, (float)tmp.y, 2, paint); } //Draw touchPointpaint.setColor(Color.RED);if(touchPoint != null)canvas.drawCircle( (float)touchPoint.x, (float)touchPoint.y, 10, paint);return;}}




然后,你需要把这个东西放在你的布局文件里,怎么用自己的view呢?前面加上包名就可以了

<com.example.remoteapp.SuperImageView     android:id="@+id/picView"     android:layout_width="fill_parent"     android:layout_height="fill_parent"     android:scaleType="center"    android:src="@drawable/pic2" />


然后,需要重绘的时候,调用一下这个类的invalidate()方法就行了,就像这样:

imageView.setOnTouchListener(new OnTouchListener(){@Overridepublic boolean onTouch(View v, MotionEvent e) {// TODO Auto-generated method stubPointType point = new PointType();        point.x=e.getX();        point.y=e.getY();        point = point.screenToView(currentDegree/180*Math.PI);        now_point = point;                imageView.setTouchPoint(now_point);//set信息        imageView.invalidate();//重画           return false;}});







0 0
原创粉丝点击