有时候,我们需要显示一定的图形,而这些图形是安卓原生的控件无法实现的,这时候我们就考虑到要用自定义Viewl来实现我们所要达到的效果。
下面我将绘制柱状图的过程讲述一下。
1.写一个类继承View重写它的构造方法
public MyView(Context context) {
super(context); }
2.重写onDraw(Canvas canvas)方法 在此方法中进行绘制
3.在xml布局中进行引用 具体代码如下:
package zm.ztd.com.rx_login; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; /** * Created by Administrator on 2017-01-01. */ public class MyView extends View{ private Paint myPaint; private static final String title="2006-2011年上半年的销售情况"; private static final String content="来自公司销售的统计数据"; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); myPaint=new Paint();//初始化画笔 myPaint.setColor(Color.BLACK); myPaint.setTextSize(18); canvas.drawText(title,20,20,myPaint); //绘制坐标 canvas.drawLine(50,100,50,500,myPaint);//绘制纵坐标(左 上 右 下) canvas.drawLine(50,500,400,500,myPaint);//绘制横坐标 int[] array={0,50,100,150,200,250,300,350}; myPaint.setTextSize(10);//设置字体大小 canvas.drawText("单位是:万元",20,90,myPaint); for(int i=0;i<array.length;i++){ canvas.drawLine(50,500-array[i],54,500-array[i],myPaint); canvas.drawText(array[i]+"",20,500-array[i],myPaint); } String[] array2={"2008年","2009","2010","2011上半年"}; for(int i=0;i<array2.length;i++){ canvas.drawText(array2[i],array[i]+80,520,myPaint); } myPaint.setColor(Color.BLUE); myPaint.setStyle(Paint.Style.FILL); canvas.drawRect(new Rect(90,500-56,110,500),myPaint); canvas.drawRect(new Rect(140,500-98,160,500),myPaint); canvas.drawRect(new Rect(190,500-207,210,500),myPaint); canvas.drawRect(new Rect(240,500-318,260,500),myPaint); myPaint.setColor(Color.BLACK); canvas.drawText("56.32",88,500-58,myPaint); canvas.drawText("90.00",138,500-100,myPaint); canvas.drawText("207.67",188,500-209,myPaint); canvas.drawText("318.56",238,500-320,myPaint); myPaint.setColor(Color.BLACK); myPaint.setTextSize(16); canvas.drawText(content,20,560,myPaint); } }
xml中引用:
<zm.ztd.com.rx_login.MyView android:layout_width="match_parent" android:layout_height="match_parent" />