更新时间:2022-01-19
DrawLine方法说明
public void drawLine(float startX, float startY,
float stopX, float stopY, @NonNull Paint paint) {
throw new RuntimeException("Stub!");
}
Canvas.drawLine参数 | 描述 |
---|---|
startX | x轴起始坐标 |
startY | y轴起始坐标 |
stopX | x轴终止坐标 |
stopY | y轴终止坐标 |
paint | Paint |
Paint的set方法 | 描述 |
---|---|
paint.setStyle | 填充方式,默认FILL填充,还有STROKE描边,FILL_AND_STROKE填充并描边 |
paint.setColor | 设置颜色 |
paint.setStrokeWidth | 设置宽度 |
paint.setAntiAlias | 防锯齿 |
演示 绘制横线和竖线
1) MyDrawLineView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
public class MyDrawLineView extends View {
public MyDrawLineView(Context context) {
super(context);
}
public MyDrawLineView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyDrawLineView(Context context, @Nullable AttributeSet attrs,
int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawCenterLineX(canvas);
drawCenterLineY(canvas);
}
/**
* 绘制x轴的中间竖线
*/
private void drawCenterLineX(Canvas canvas){
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
paint.setStrokeWidth(2);
canvas.drawLine(getWidth()/2, 0, getWidth()/2, getHeight(), paint);
}
/**
* 绘制y轴的中间横线
*/
private void drawCenterLineY(Canvas canvas){
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.BLUE);
paint.setStrokeWidth(2);
canvas.drawLine(0, getHeight()/2, getWidth(), getHeight()/2, paint);
}
}
2) xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.example.mydrawlinetest.MyDrawLineView
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
3) 效果
4) 测试代码
MyDrawLineTest: 地址
参考文档:
Android Developers 中描述的 Canvas.drawLine方法,参考文档: 地址
DrawText博文参考:地址