实现的自定义控件效果图:
实现步骤:
1.创建一个CustomerView类继承自实现DrawTask(绘制任务,并任务接口):
public class CustomerView extends Component 实现 DrawTask;
2. 自定义其构造CustomerView context(Context, AttrSet attr Set),添加绘制任务addDrawTask(this):
公共客户视图(时间地点,AttrSet attrSet){
超级(时间,attrSet);
addDrawTask(这个);
}
3.实现接口DrawTask的方法onDraw():
public void onDraw(组件,画布){
//这个自定义控件的绘制过程,比如一个圆
油漆油漆=新油漆();//创建画笔
paint.setColor(Color.GREEN); //设置画笔颜色
paint.setStyle(Style.FILL_STYLE); //设置画笔填充样式,这里用实心样式;还有空心样式
油漆.setStrokeWidth( 8 ); //设置画笔粗细大小
paint.setText( 60 );/Size/绘制文字时,设置文字大小
canvas.drawle( 600 , 400 , 100 ,paint);/使用canvas画布完成paintCircle,参数600,400表示圆心的x,y坐标,100圆的绘图,为设置的笔画
}
4.在xml布局中引用自定义控件:
<方向布局
xmlns:ohos
ohos:height = "match_parent"
哦,方向= “纵向”
ohos:width = "match_parent" >
< com.isoftstone.zeldemo.CustomerView
ohos:height = "match_content"
ohos:width = "match_content" />
方向布局>
自定义控件实现类源代码:
package com.isoftstone.zeldemo;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Component.DrawTask;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Paint.Style;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;
import ohos.app.Context;
public class CustomerView extends Component implements DrawTask {
public CustomerView(Context context, AttrSet attrSet) {
super(context, attrSet);
addDrawTask(this);
}
@Override
public void onDraw(Component component, Canvas canvas) {
Paint paint=new Paint();
paint.setColor(Color.GREEN);
paint.setStyle(Style.FILL_STYLE);
paint.setStrokeWidth(8);
paint.setTextSize(60);
canvas.drawCircle(600,400,100,paint);
paint.setColor(Color.BLACK);
Point pointStart1=new Point((float)700,(float)400);
Point pointEnd1=new Point((float)1000,(float)400);
canvas.drawLine(pointStart1,pointEnd1,paint);
Point pointEnd2=new Point((float)800,(float)600);
canvas.drawLine(pointEnd1,pointEnd2,paint);
Point pointEnd3=new Point((float)900,(float)800);
canvas.drawLine(pointEnd2,pointEnd3,paint);
paint.setColor(Color.RED);
canvas.drawCircle(900,900,100,paint);
paint.setColor(Color.BLACK);
Point pointEnd4=new Point((float)800,(float)900);
Point pointEnd5=new Point((float)400,(float)900);
canvas.drawLine(pointEnd4,pointEnd5,paint);
paint.setColor(Color.YELLOW);
canvas.drawCircle(300,900,100,paint);
paint.setColor(Color.BLACK);
Point pointEnd6=new Point((float)300,(float)800);
Point pointEnd7=new Point((float)400,(float)600);
canvas.drawLine(pointEnd6,pointEnd7,paint);
Point pointEnd8=new Point((float)200,(float)400);
canvas.drawLine(pointEnd7,pointEnd8,paint);
Point pointEnd9=new Point((float)500,(float)400);
canvas.drawLine(pointEnd8,pointEnd9,paint);
canvas.drawText(paint,"自定义图形",(float) 450,(float)630);
}
}
|