RelativeLayout圆角处理

RelativeLayout圆角处理以后,可以变相对子view进行圆角处理,如ImageView,VideoView等

 

RoundRelativeLayout具体实现

比较简单,只需要在初始化时设置一下layout的ViewOutlineProvider,方便起见,这里写死radius为20dp 

/**
 * 一个可以把RelativeLayout裁剪成圆角的自定义RelativeLayout布局
 * 由于layout里面的子view同样会被裁剪,例如VideoView,ImageView等,很实用
 *
 * created by luninggithub
 */
public class RoundRelativeLayout extends RelativeLayout {

    private static final int DEFAULT_ROUND_SIZE = 20;

    public RoundRelativeLayout(Context context) {
        this(context, null);
    }

    public RoundRelativeLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        this(context, attrs, defStyleAttr, 0);
    }

    public RoundRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        RoundViewOutlineProvider outlineProvider = new RoundViewOutlineProvider(ScreenUtil.dp2px(DEFAULT_ROUND_SIZE));
        setOutlineProvider(outlineProvider);
        setClipToOutline(true);
    }

    /**
     * 圆角ViewOutlineProvider
     */
    private static class RoundViewOutlineProvider extends ViewOutlineProvider {
        private final int roundSize;

        public RoundViewOutlineProvider(int roundSize) {
            this.roundSize = roundSize;
        }

        @Override
        public void getOutline(View view, Outline outline) {
            outline.setRoundRect(0, 0, view.getWidth(), view.getHeight(), roundSize);
        }
    }
}

关键类ViewOutlineProvider

ViewOutlineProvider是一个抽象类,系统预定义了三种不同的outlineprovider,我们只需要实现getOutline方法,在方法内部设置自定义的outline即可。

package android.view;

import android.graphics.Outline;
import android.graphics.drawable.Drawable;

/**
 * Interface by which a View builds its {@link Outline}, used for shadow casting and clipping.
 */
public abstract class ViewOutlineProvider {
    // 省略系统预定义的ViewOutlineProvider代码...
    
    /**
     * Called to get the provider to populate the Outline.
     *
     * This method will be called by a View when its owned Drawables are invalidated, when the
     * View's size changes, or if {@link View#invalidateOutline()} is called
     * explicitly.
     *
     * The input outline is empty and has an alpha of <code>1.0f</code>.
     *
     * @param view The view building the outline.
     * @param outline The empty outline to be populated.
     */
    public abstract void getOutline(View view, Outline outline);
}

由注释可知,getOutline会在view主动调invalidateOutline()方法是被调用

RoundRelativeLayout在初始化int是,会设置自定义的outlineprovider:setOutlineProvider(outlineProvider);

有系统代码可知,setOutlineProvider方法会主动调用,如下:

// 省略View的其他代码......
/**
 * Sets the {@link ViewOutlineProvider} of the view, which generates the Outline that defines
 * the shape of the shadow it casts, and enables outline clipping.
 * <p>
 * The default ViewOutlineProvider, {@link ViewOutlineProvider#BACKGROUND}, queries the Outline
 * from the View's background drawable, via {@link Drawable#getOutline(Outline)}. Changing the
 * outline provider with this method allows this behavior to be overridden.
 * <p>
 * If the ViewOutlineProvider is null, if querying it for an outline returns false,
 * or if the produced Outline is {@link Outline#isEmpty()}, shadows will not be cast.
 * <p>
 * Only outlines that return true from {@link Outline#canClip()} may be used for clipping.
 *
 * @see #setClipToOutline(boolean)
 * @see #getClipToOutline()
 * @see #getOutlineProvider()
 */
public void setOutlineProvider(ViewOutlineProvider provider) {
    mOutlineProvider = provider;
    invalidateOutline(); // 这里会主动调用自定义的getOutline方法
}
// 省略View的其他代码......
/**
 * Called to rebuild this View's Outline from its {@link ViewOutlineProvider outline provider}
 *
 * @see #setOutlineProvider(ViewOutlineProvider)
 */
public void invalidateOutline() {
    rebuildOutline();// 见下面方法

    notifySubtreeAccessibilityStateChangedIfNeeded();
    invalidateViewProperty(false, false);
}
// 省略View其他代码......
private void rebuildOutline() {
    // Unattached views ignore this signal, and outline is recomputed in onAttachedToWindow()
    if (mAttachInfo == null) return;

    if (mOutlineProvider == null) {
        // no provider, remove outline
        mRenderNode.setOutline(null);
    } else {
        final Outline outline = mAttachInfo.mTmpOutline;
        outline.setEmpty();
        outline.setAlpha(1.0f);

        mOutlineProvider.getOutline(this, outline); // 这里调用
        mRenderNode.setOutline(outline); // 见下面方法
    }
}


/**
 * Sets the outline, defining the shape that casts a shadow, and the path to
 * be clipped if setClipToOutline is set.
 *
 * This will make a copy of the provided {@link Outline}, so any future modifications
 * to the outline will need to call {@link #setOutline(Outline)} with the modified
 * outline for those changes to be applied.
 *
 * @param outline The outline to use for this RenderNode.
 * @return True if the value changed, false if the new value was the same as the previous value.
 */
public boolean setOutline(@Nullable Outline outline) {
    if (outline == null) {
        return nSetOutlineNone(mNativeRenderNode);
    }

    switch (outline.mMode) {
        case Outline.MODE_EMPTY:
            return nSetOutlineEmpty(mNativeRenderNode);
        case Outline.MODE_ROUND_RECT: // 走到这里
            return nSetOutlineRoundRect(mNativeRenderNode,
                    outline.mRect.left, outline.mRect.top,
                    outline.mRect.right, outline.mRect.bottom,
                    outline.mRadius, outline.mAlpha);
        case Outline.MODE_PATH:
            return nSetOutlinePath(mNativeRenderNode, outline.mPath.mNativePath,
                    outline.mAlpha);
    }

    throw new IllegalArgumentException("Unrecognized outline?");
}
// 省略View代码......


public final class RenderNode {

	// 省略无关代码...
	@CriticalNative
	private static native boolean nSetOutlineRoundRect(long renderNode, int left, int top,
        	int right, int bottom, float radius, float alpha);
}

这样一看就比较清晰了

init -→ setOutlineProvider  -→ invalidateOutline  -→ rebuildOutline   -→ setOutline -→ nSetOutlineRoundRect(Native接口)

Demo参考github:LnCustomViews

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RelativeLayout背景为圆角矩形的实现可以通过自定义一个继承自RelativeLayout的类,并在其中重写onDraw方法来实现。 您可以按照以下步骤来实现RelativeLayout背景为圆角矩形: 1. 创建一个新的Java类,例如RoundBGRelativeLayout,继承自RelativeLayout。 2. 在RoundBGRelativeLayout类中,重写onDraw方法。 3. 在onDraw方法中,创建一个RectF对象,并设置其大小为当前视图的宽度和高度。 4. 使用Paint对象设置绘制的颜色和样式,例如设置为圆角矩形。 5. 调用Canvas对象的drawRoundRect方法,以绘制圆角矩形背景。 6. 在布局文件中,使用RoundBGRelativeLayout作为RelativeLayout的子元素,并设置相关属性,例如设置圆角矩形的半径。 下面是一个示例代码,展示了如何实现RelativeLayout背景为圆角矩形: ```java public class RoundBGRelativeLayout extends RelativeLayout { private Paint paint; private RectF rect; public RoundBGRelativeLayout(Context context) { this(context, null); } public RoundBGRelativeLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RoundBGRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } private void init() { paint = new Paint(); paint.setColor(Color.WHITE); paint.setAntiAlias(true); paint.setStyle(Paint.Style.FILL); } @Override protected void onDraw(Canvas canvas) { rect = new RectF(0, 0, getWidth(), getHeight()); float cornerRadius = getResources().getDimension(R.dimen.corner_radius); canvas.drawRoundRect(rect, cornerRadius, cornerRadius, paint); super.onDraw(canvas); } } ``` 在布局文件中使用RoundBGRelativeLayout作为RelativeLayout的子元素,并设置相关属性,例如设置圆角矩形的半径: ```xml <com.example.background.RoundBGRelativeLayout android:id="@id/container" android:layout_width="fill_parent" android:layout_height="300dp" lwd:custom_background="@drawable/bg" lwd:corner_radius="16dp"> <!-- 其他子视图 --> </com.example.background.RoundBGRelativeLayout> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值