继承android.view.View自定义view,使用画笔绘制view示例
2013-01-17 10:20
701 查看
布局xml:
activity代码:
自定义view示例代码:
由以下运行图可见,自定义view的原点(0,0)由该view的左上角开始,由该view的右下角结束
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/testcontainer" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> <com.gifor.CustomView android:id="@+id/customView1" android:layout_width="100dp" android:layout_height="100dp" /> </LinearLayout>
activity代码:
import android.app.Activity; import android.os.Bundle; import android.widget.LinearLayout; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout ll = (LinearLayout)this.findViewById(R.id.testcontainer);//xml布局方式加载自定义view ll.addView(new CustomView(this));//代码方式加载自定义view } }
自定义view示例代码:
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 CustomView extends View { Paint linePaint; public CustomView(Context context) { super(context); /* *初始化画笔 */ linePaint = new Paint(); linePaint.setColor(Color.BLUE);//设置画笔颜色 linePaint.setAntiAlias(true);//设置画笔是否抗锯齿 linePaint.setStrokeWidth(10);//设置画笔粗细 } public CustomView(Context context, AttributeSet attr) {//使用xml布局绘制自定义view必须有此构造方法 super(context, attr); /* *初始化画笔 */ linePaint = new Paint(); linePaint.setColor(Color.BLACK);//设置画笔颜色 linePaint.setAntiAlias(true);//设置画笔是否抗锯齿 linePaint.setStrokeWidth(10);//设置画笔粗细 } @Override protected void onDraw(Canvas canvas) { canvas.drawLine(0, 0, this.getWidth(), this.getHeight(), linePaint);//从view左上角到view右下角画线 canvas.drawLine(this.getWidth(), 0, 0, this.getHeight(), linePaint);//从view右上角到view左下角画线 super.onDraw(canvas); } }
由以下运行图可见,自定义view的原点(0,0)由该view的左上角开始,由该view的右下角结束
相关文章推荐
- Android使用自定义View继承SurfaceView实现动态折线图的绘制
- Android使用自定义View继承SurfaceView实现动态折线图的绘制
- Android 自定义View及其在布局文件中的使用示例
- Android 自定义View使用示例(三)
- Android自定义View之使用Path绘制手势轨迹和水波效果
- Android 自定义View及其在布局文件中的使用示例
- Android中自定义View中的使用与绘制技巧
- Android中使用自定义View实现shape图形绘制
- Android 自定义View及其在布局文件中的使用示例(二)
- Android自定义View之继承TextView绘制背景
- Android 自定义View使用示例(二)
- Android 自定义View及其在布局文件中的使用示例
- Android基于OpenGL在GLSurfaceView上绘制三角形及使用投影和相机视图方法示例
- Android 自定义View及其在布局文件中的使用示例
- Android使用自定义View绘制渐隐渐现动画
- Android开发使用自定义View将圆角矩形绘制在Canvas上的方法
- Android编程使用自定义View实现水波进度效果示例
- Android 自定义View及其在布局文件中的使用示例
- Android 自定义View及其在布局文件中的使用示例(三):结合Android 4.4.2_r1源码分析onMeasure过程
- Android 自定义 View 绘制