Android 设置任意View的背景为圆形或圆角
我的需求主要还是在SurfaceView需要设置为圆形背景,在网上找了下,发现一个可行方法,做个记录
import android.graphics.Outline;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewOutlineProvider;
public class TextureVideoViewOutlineProvider extends ViewOutlineProvider {
private float mRadius;
public TextureVideoViewOutlineProvider(float radius) {
this.mRadius = radius;
}
@Override
public void getOutline(View view, Outline outline) {
Rect rect = new Rect();
view.getGlobalVisibleRect(rect);
int leftMargin = 0;
int topMargin = 0;
Rect selfRect = new Rect(leftMargin, topMargin,
rect.right - rect.left - leftMargin, rect.bottom - rect.top - topMargin);
outline.setRoundRect(selfRect, mRadius);
}
}
使用的时候传任意一个view对象设置即可,如下例子:
mView.setOutlineProvider(new TextureVideoViewOutlineProvider(radius));
mView.setClipToOutline(true);
任何view都可以通过此方法设置,如果想要变为圆形,可以将圆角设置为组件宽度的一半(当然组件的宽高是1:1的正方形)