如何在Android中绘制矩形?

时间:2017-12-25 00:45:52

标签: android drawrect

我试图制作带有我的徽标的自定义横幅。 This is what I want it to look like.我已经尝试了多种方法,但它们似乎没有用。以下是我的尝试。

这是CustomView类:

import android.view.View;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;

/**
 * Created by Michael on 12/24/2017.
 */

public class CustomView extends View {
private Rect rectangle;
private Paint paint;

public CustomView(Context context) {
    super(context);
    int x = 50;
    int y = 50;
    int sideLength = 200;

    // create a rectangle that we'll draw later
    rectangle = new Rect(x, y, sideLength, sideLength);

    // create the Paint and set its color
    paint = new Paint();
    paint.setColor(Color.GRAY);
}

@Override
protected void onDraw(Canvas canvas) {
    canvas.drawColor(Color.BLUE);
    canvas.drawRect(rectangle, paint);
  }
}

这是MainActivity类:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(new CustomView(this));

  }
}

编辑:我目前的做法什么也没做。当前代码对应用程序的布局没有影响。

1 个答案:

答案 0 :(得分:0)

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="rectangle"  >

            <solid android:color="@color/myColor" />

        </shape>
    </item>

    <item>
        <bitmap android:src="@drawable/myLogo" />
    </item>

</layer-list>

你可以尝试这样的事情。将此drawable设置为framelayout的背景。