如何在Android中使用画布进行绘制?

问题描述 投票:0回答:1

我跟踪了一个视频,但最终还是这样做了,但不知道出什么错了,最终结果是空白的布局。

我只想创建一个自定义视图并尝试绘制它。以下视频中,我设置了所有属性,确切的区别只是他将它设置为圆,而我设置为矩形。

MainActivity.java

public class MainActivity extends AppCompatActivity {
CustomViews customViews;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    customViews = (CustomViews) findViewById(R.id.customButtonView);
    customViews.setRectangleProperties(140.0f, 120.0f, 140.0f, 120.0f);
    customViews.draw();
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<com.prod.tryingnew.views.CustomViews
    android:id="@+id/customButtonView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</RelativeLayout>

CustomViews.Java

public class CustomViews extends View {
private float left,top,right,bottom;
Paint paint=new Paint();

public CustomViews(Context context) {
    super(context);
}

public CustomViews(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

public CustomViews(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public void setRectangleProperties(float left,float top,float right,float bottom){
    this.left=left;
    this.top=top;
    this.right=right;
    this.bottom=bottom;
}

public void draw(){
    invalidate();//It invalidates whole view
    requestLayout();
}

@Override
protected void onDraw(Canvas canvas) {
    paint.setStrokeWidth(20);
    paint.setColor(Color.RED);
    canvas.drawRect(left,top,right,bottom,paint);
    super.onDraw(canvas);
    }
}
android android-canvas
1个回答
0
投票

我在开始的同一位置开始和结束绘图路径。

customViews.setRectangleProperties(140.0f, 120.0f, 140.0f, 120.0f);

to

 customViews.setRectangleProperties(140, 120, 240, 160);
© www.soinside.com 2019 - 2024. All rights reserved.