在Android中,通過setOutlineProvider
方法可以為視圖(View)設置輪廓(Outline)提供者,從而實現陰影效果
ViewOutlineProvider
類,繼承自ViewOutlineProvider
。import android.graphics.Outline;
import android.view.View;
import android.view.ViewOutlineProvider;
public class CustomOutlineProvider extends ViewOutlineProvider {
private int width;
private int height;
public CustomOutlineProvider(int width, int height) {
this.width = width;
this.height = height;
}
@Override
public void getOutline(View view, Outline outline) {
outline.setRect(0, 0, width, height);
}
}
TextView
。 android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
OutlineProvider
。import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView);
int width = textView.getWidth();
int height = textView.getHeight();
// 設置OutlineProvider
CustomOutlineProvider customOutlineProvider = new CustomOutlineProvider(width, height);
textView.setOutlineProvider(customOutlineProvider);
// 開啟硬件加速
textView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
// 設置陰影
textView.setElevation(8);
}
}
注意:在設置陰影之前,需要確保視圖已經測量完成??梢栽?code>onCreate方法中使用ViewTreeObserver
來監聽視圖的測量完成事件。
textView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
// 獲取視圖的寬度和高度
int width = textView.getWidth();
int height = textView.getHeight();
// 設置OutlineProvider
CustomOutlineProvider customOutlineProvider = new CustomOutlineProvider(width, height);
textView.setOutlineProvider(customOutlineProvider);
// 開啟硬件加速
textView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
// 設置陰影
textView.setElevation(8);
// 移除監聽器
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
textView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
textView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
這樣,你就可以通過setOutlineProvider
方法為視圖設置陰影效果了。