标签:android style blog http color width
1.创建继承view的类
1 public class myview extends View{ 2 3 public myview(Context context, AttributeSet attrs) { //构造器 4 super(context, attrs); 5 // TODO Auto-generated constructor stub 6 } 7 8 protected void onDraw(Canvas canvas) 9 { 10 super.onDraw(canvas); 11 canvas.drawColor(Color.BLACK); //绘制黑色背景 12 Paint paint=new Paint(); //创建画笔 13 paint.setColor(Color.RED); 14 canvas.drawRect(10,10,110,110, paint); //画矩形 15 canvas.drawText("这是字符串", 10, 130, paint);//写字 16 RectF rf1=new RectF(10,130,110,230); //定义一个矩形 17 canvas.drawArc(rf1, 0, 45, true, paint);//画弧,顺时针 18 canvas.drawLine(150, 10, 250, 110, paint);//画线 19 RectF rf2=new RectF(150,130,250,230); 20 canvas.drawOval(rf2, paint); //画圆 21 22 } 23 24 }
上述是一个例子。
2.要调用这个myview,需要在layout.xml上调用,如
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <com.example.myview.myview android:id="@+id/myview" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </RelativeLayout>
com.example.myview是myview这个类的所在包,xml调用时,记得前面要加上包。
这个是另一个自定义view的例子
1 package com.example.myview; 2 3 import android.content.Context; 4 import android.graphics.Bitmap; 5 import android.graphics.BitmapFactory; 6 import android.graphics.Canvas; 7 import android.graphics.Color; 8 import android.graphics.Paint; 9 import android.util.AttributeSet; 10 import android.view.View; 11 12 public class myview_picture extends View{ 13 Bitmap mb; 14 Paint paint; 15 16 public myview_picture(Context context, AttributeSet attrs) { 17 super(context, attrs); 18 // TODO Auto-generated constructor stub 19 this.initBitmap(); //初始化图片 20 } 21 22 public void initBitmap() 23 { 24 paint=new Paint(); 25 mb=BitmapFactory.decodeResource(getResources(), R.drawable.indexgundom); 26 } 27 @Override 28 protected void onDraw(Canvas canvas) 29 { 30 super.onDraw(canvas); 31 paint.setAntiAlias(true); //打开抗锯齿 32 paint.setColor(Color.WHITE); //设置画笔颜色 33 paint.setTextSize(15); //我猜是设置字体大小 34 canvas.drawBitmap(mb, 10,10, paint); //画图 35 canvas.drawText("图片的宽度:"+mb.getWidth(), 20, 220, paint); //写字 36 canvas.drawText("图片的高度"+mb.getHeight(), 150, 220, paint); 37 } 38 39 40 }
android-自定义view创建概述,布布扣,bubuko.com
标签:android style blog http color width
原文地址:http://www.cnblogs.com/lexious/p/3857575.html