Android学习第四篇——使用绘图API自定义视图

来源:互联网 发布:淘宝卖家查看开店时间 编辑:程序博客网 时间:2024/06/05 17:38

这一次练习我需要完成的效果就是一个正方形绕着中心点旋转



首先我们需要创建一个类,一个定义控件的类,并且继承自ViewRotatingRect.class

public class RotatingRect extends View {public RotatingRect(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}public RotatingRect(Context context, AttributeSet attrs) {super(context, attrs);}public RotatingRect(Context context) {super(context);}}
这里需要重写所有的构造函数

然后我们需要重写draw函数,用于绘制图形

@Overridepublic void draw(Canvas canvas) {super.draw(canvas);canvas.drawRect(0, 0, 100, 100, p);}
接着我们自定义一个函数initProperties(),并且在之前所有的构造函数中调用该方法

private Paint p;private float degrees = 0;//设置旋转的角度,之后会用到private void initProperties(){p=new Paint();p.setColor(Color.RED);}

这样我们就完成了一个颜色为红色的正方形,然后我们需要在布局中调用该类

调用的方法是<com.包名.程序名.类名></com.包名.程序名.类名>

<com.example.custombutton.RotatingRect        android:layout_width="fill_parent"        android:layout_height="fill_parent">    </com.example.custombutton.RotatingRect>
这样写了以后我们就能在界面上看到红色的正方形了,但是此时这个正方形还不能旋转,接下来我们的目标就是让他旋转起来。

我们回到之前的RotatingRect类中来

@Overridepublic void draw(Canvas canvas) {super.draw(canvas);canvas.drawRect(0, 0, 100, 100, p);System.out.println(">>>>>>>>>>>");}
我们输出一下,我们会看到在控制台中只输出了一次


而我们需要让一个图片旋转起来那就需要不停的,反复的执行,所以我们在该方法中加上这么一句

//使这个View无效,这样就会使的程序不断的重绘invalidate();
这样以后还是不够的,我们还没有让他动起来,所以我们还需要修改,最后的方法就成这样了
@Overridepublic void draw(Canvas canvas) {super.draw(canvas);canvas.save();//调整位置(200,200)//canvas.rotate(degrees);canvas.translate(200, 200);//设置旋转的角度,以及旋转的中心点canvas.rotate(degrees,50,50);//绘制初始的图形的样子canvas.drawRect(0, 0, 100, 100, p);degrees++;canvas.restore();//System.out.println(">>>>>>>>>>>");//使这个View无效,这样就会使的程序不断的重绘invalidate();}

最后我们来看一下RotatingRect.class的完整代码

package com.example.custombutton;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 RotatingRect extends View {public RotatingRect(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);initProperties();}public RotatingRect(Context context, AttributeSet attrs) {super(context, attrs);initProperties();}public RotatingRect(Context context) {super(context);initProperties();}private Paint p;private float degrees = 0;private void initProperties(){p=new Paint();p.setColor(Color.RED);}@Overridepublic void draw(Canvas canvas) {super.draw(canvas);canvas.save();//调整位置(200,200)//canvas.rotate(degrees);canvas.translate(200, 200);//设置旋转的角度,以及旋转的中心点canvas.rotate(degrees,50,50);//绘制初始的图形的样子canvas.drawRect(0, 0, 100, 100, p);degrees++;canvas.restore();//System.out.println(">>>>>>>>>>>");//使这个View无效,这样就会使的程序不断的重绘invalidate();}}

这样我们在模拟器中打开就可以看到想要的效果了

0 0
原创粉丝点击