Wrong Y axis when drawing on canvas

时间:2015-06-15 14:23:06

标签: java android android-canvas

I am trying to draw on a canvas but the Y axis appears to be wrong. It looks like 0 is actually -100.

For example, when I draw a red square that is 10 px from every border I get the following square:

enter image description here

The code I am using:

    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    paint.setStyle(Paint.Style.FILL);
    canvas.drawRect(10, 10, canvas.getWidth() - 10, canvas.getHeight() - 10, paint);

My layout:

<?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">

    <include layout="@layout/toolbar" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:background="@color/facebook_color"
                android:id="@+id/catchImage"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:scaleType="fitCenter"
                android:layout_marginBottom="20dp"
                android:adjustViewBounds="true"  />

            <View
                android:background="@color/news_item_seperator_stroke"
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                />
        </LinearLayout>

    </ScrollView>
</LinearLayout>

When I use the following code everything works fine:

Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(0, 0, canvas.getWidth()/2, canvas.getHeight()/2, paint);

Paint paint2 = new Paint();
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL);
canvas.drawRect(canvas.getWidth()/2, canvas.getHeight()/2, canvas.getWidth(), canvas.getHeight(), paint2);

http://i.imgur.com/54JwLfR.png

2 个答案:

答案 0 :(得分:1)

Your code is fine, your canvas is just bigger than the current screen. Check your layout xml. Remember: The coordinates are relative to the canvas and not relative to the visible part of it.

答案 1 :(得分:0)

Canvas canvas = new Canvas(bitmap);

您正在从位图生成画布,这意味着Bitmap可以是任何大小,而不是视图。

您应该使用getWidth()和getHeight()

从View中获取宽度/高度