自定义View画圆,画扇形
创建一个类继承自View
public class lhjclass extends View {
public lhjclass(Context context) {
super(context);
}
public lhjclass(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public lhjclass(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//创建画笔
Paint paint = new Paint();
//设置画笔颜色
paint.setColor(Color.WHITE);
//设置画笔线条
paint.setStrokeWidth(20);
//设置样式STROKE(空心),FILL(实心)
paint.setStyle(Paint.Style.STROKE);
//画扇形(true,false表示扇形两边的线是否显示)
canvas.drawArc(320,180,570,430,90,270,false,paint);
//同心圆
/* paint.setColor(Color.WHITE);
canvas.drawCircle(450,300,180,paint);//画圆
paint.setColor(Color.GREEN);
canvas.drawCircle(450,300,150,paint);*/
}
}
布局直接使用
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.a1225.lhjclass
android:layout_width="wrap_content"
android:layout_height="300dp"
android:background="#1AFF00"
></com.example.a1225.lhjclass>
</LinearLayout>
效果图

进度条
public class HomeView extends View {
private int count=0;
public HomeView(Context context) {
super(context);
}
public HomeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public HomeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
//画一个空心圆
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setStrokeWidth(20);
paint.setStyle(Paint.Style.STROKE);
canvas.drawArc(250,250,600,600,0,count,false,paint);
//每秒发送一下作为延时
handler.sendEmptyMessage(1);
}
private Handler handler=new Handler(){
@Override
public void dispatchMessage(@NonNull Message msg) {
super.dispatchMessage(msg);
if (count<=360){
count=count+1;
handler.sendEmptyMessageDelayed(1,1000);
invalidate();
}
}
};
}
博客主要介绍了在Android开发中自定义View的相关内容,包括如何使用自定义View来画圆、画扇形,还提及了进度条相关,属于移动开发领域的技术内容。


被折叠的 条评论
为什么被折叠?



