Android 画布学习Canvas (1)坐标

来源:互联网 发布:java中单选按钮 编辑:程序博客网 时间:2024/06/08 04:03

想使用Canvas 必须先弄清楚Canvas 的坐标系,我们先弄清楚Canvas 的坐标原点

Canvas 坐标问题

先简单定义一个View;

public class StudyView extends View {
    private Paint paint;
    public StudyView(Context context) {
        super(context);
    }
    public StudyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        paint.setColor(Color.RED);
    }
    public StudyView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(Color.BLUE);
        canvas.drawRect(new Rect(0,0,100,100),paint);
        super.onDraw(canvas);
    }

}

我在画布中创建了一个矩形,这个矩形的坐标是从坐标原点位置开始画,因为我坐标起始的位置为0,0,然后看布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <com.example.zhujie.myapplication.StudyView
        android:id="@+id/studyview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
</LinearLayout>


虽然红色矩形在屏幕的最做上方,但原点并不是在原点的左上方,接下来我再次修改布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <com.example.zhujie.myapplication.StudyView
        android:id="@+id/studyview"
        android:layout_width="200dp"
        android:layout_height="200dp"/>
</LinearLayout>


很明显绿色矩形并不是在屏幕的左上角而是在控件的左上角,由此实验可以证明Canvas的左边并不是在屏幕的做上方而是在控件画布的左上方。

1 0
原创粉丝点击