1. 概述
Android画图最基本的三个对象( Color, Paint, Canvas),三个类都在android.graphics包下
1)Color:颜色对象
2)Paint:画笔对象
3)Canvas:画布对象
三者相结合,就能画出基本的图形。
2. 常用方法
1)Color: setColor(int color) Set the paint's color.
setARGB(int a, int r, int g, int b)Helper to setColor(), that takes a, r, g, b and constructs the color int
setAlpha(int a)Helper to setColor(), that only assigns the color's alpha value, leaving its r, g, b values unchanged.
2) Paint:
3)Canvas: drawLine(float startX, float startY, float stopX, float stopY, Paint paint) 画直线
drawRect(float left, float top, float right, float bottom, Paint paint)画矩形
drawCircle(float cx, float cy, float radius, Paint paint)画圆形
3. 自定义视图
1)需要继承View这个类,所有的组件都是继承于这个类
2)并要实现一个带Context参数的构造函数,因为父类中,没有隐式无参数的构造函数
3)需要重写父类中的onDraw()方法,一切的画图操作将在这进行
具体代码:
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="20dp"
android:orientation="horizontal" >
<view
android:id="@+id/view1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
class="com.charein.util.TimelineView" />
</LinearLayout>
package com.charein.util;
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 TimelineView extends View {
public TimelineView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public TimelineView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(5);
canvas.drawLine(20, 20, 20, 200, paint);
paint.setTextSize(30);
canvas.drawText("notice", 40, 40, paint);
super.onDraw(canvas);
}
}
效果图: