ShapeDrawable是Android平台提供的一個自定義圖形繪製類,可以通過ShapeDrawable繪製出多種圖形:矩形、圓角矩形、橢圓形、圓形、扇形等。本文主要介紹如何使用ShapeDrawable繪製出圓形背景。
一、準備工作
在使用ShapeDrawable之前,需要有以下幾個條件:
1、在xml文件中定義ShapeDrawable資源。
2、在Java類中調用findViewById()方法獲取要設置背景的View。
3、調用View.setBackground()方法將ShapeDrawable資源設置為背景。
下面是一個簡單的布局文件,在其中添加一個TextView用於展示圓形背景:
<?xml version="1.0" encoding="utf-8"?>
<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">
<TextView
android:id="@+id/tv_circle"
android:layout_width="100dp"
android:layout_height="100dp"
android:text="Hello World!"
android:textSize="20sp"
android:gravity="center"
android:layout_centerInParent="true"/>
</RelativeLayout>
二、使用ShapeDrawable繪製圓形背景
下面是一個示例代碼,使用ShapeDrawable繪製圓形背景:
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private TextView mTvCircle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTvCircle = findViewById(R.id.tv_circle);
// 創建OvalShape對象,繪製出一個圓形
OvalShape ovalShape = new OvalShape();
ShapeDrawable drawable = new ShapeDrawable(ovalShape);
drawable.getPaint().setColor(getResources().getColor(R.color.colorAccent));// 設置背景顏色
mTvCircle.setBackground(drawable);// 將ShapeDrawable設置為背景
}
}
上述代碼中:
1、創建OvalShape對象,用於繪製圓形。
2、使用OvalShape對象創建一個ShapeDrawable對象。
3、設置ShapeDrawable對象的顏色。
4、調用TextView的setBackground()方法,將ShapeDrawable對象設置為背景。
三、總結
通過本文的介紹,我們學習了如何使用ShapeDrawable繪製出圓形背景。除了圓形背景,ShapeDrawable還可以繪製出矩形、圓角矩形、橢圓形、扇形等多種形狀的圖形。利用ShapeDrawable,我們可以輕鬆實現View的自定義背景,提高用戶界面的美觀性和實用性。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/193083.html