本文介绍了使用Android绘图API开发自定义视图控件,主要包括:
1.自定义视图属性
2.自定义控件皮肤
3.使用绘图API自定义视图
详细代码:自定义视图控件
1.自定义视图属性
创建自定义类继承自view,
//由资源解析程序使用的构造方法
publicMyRect(Context context,AttributeSet attrs) {
super(context,attrs);
override此构造方法后,可在布局资源文件中访问
android:layout_width="100dp"
android:layout_height=“100dp"
设置属性时,创建values的xml文件,并设置名为rect_color的颜色属性
在供资源解析程序访问的构造方法中设置颜色:
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.MyView);
intcolor = ta.getColor(R.styleable.MyView_rect_color,0xffff0000);
setBackgroundColor(color);
//使用完之后回收
ta.recycle();
更改默认的颜色赋值
添加命名空间
xmlns:bss="http://schemas.android.com/apk/res-auto"
在相关组件内设置颜色:
bss:rect_color="#ff00ff00"/>
红色:“0xffff0000” 绿色:“0xff00ff00” 蓝色:“0xff0000ff”
2.自定义控件皮肤
通过background属性设置控件的背景皮肤
android:background="@drawable/button_skin"
通过新建drawable 选择country code类型的xml文件设置控件不同状态下的皮肤
http://schemas.android.com/apk/res/android">
图为设置button按下与不按下时的皮肤
3.使用绘图API自定义视图
创建自定义类,继承自view,重写draw方法进行绘制
canvas.save();
// canvas.rotate(degrees);默认左上角旋转
//移动位置
canvas.translate(200,200);
canvas.rotate(degrees,50,50);
canvas.drawRect(0,0,100,100,paint);
degrees++;
canvas.restore();
//使view无效,不断执行draw方法
invalidate();
需要初始化画笔paint,invalidate使得view无效,不断的重新绘制
//初始化属性
private voidinitProperties()
完成绘制后,在布局资源中,添加这个view
android:layout_width="match_parent"
android:layout_height="match_parent"/>
网友评论