android 画直线
时间: 2023-06-30 07:21:31 浏览: 55
在 Android 中,你可以使用 Canvas 和 Paint 类来画直线。下面是一个简单的示例:
```java
public class LineView extends View {
private Paint paint;
public LineView(Context context) {
super(context);
init();
}
public LineView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(5);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawLine(0, 0, canvas.getWidth(), canvas.getHeight(), paint);
}
}
```
在这个示例中,我们创建了一个继承自 View 的自定义视图类 LineView。在构造函数和 init() 方法中,我们初始化了一个 Paint 对象,并设置了它的颜色和线宽。在 onDraw() 方法中,我们使用 Canvas 的 drawLine() 方法画了一条直线,起点坐标为 (0, 0),终点坐标为 (canvas.getWidth(), canvas.getHeight())。
你可以将 LineView 添加到你的布局中,例如:
```xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.example.LineView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<!-- other views -->
</LinearLayout>
```
这样,你就可以在你的应用程序中画一条直线了。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)