继承android.view.View自定义view,使用画笔绘制view示例

来源:互联网 发布:淘宝客通用计划乱扣费 编辑:程序博客网 时间:2024/05/29 16:48


布局xml:

<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 {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);LinearLayout ll = (LinearLayout)this.findViewById(R.id.testcontainer);//xml布局方式加载自定义viewll.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);//设置画笔粗细}@Overrideprotected 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的右下角结束



原创粉丝点击