Google 还发布了这个库? 告别shape、各种 drawable...

Google 还发布了这个库? 告别shape、各种 drawable...

效果

image

前言

先来看一下ShapeableImageView是什么?

image

由上图可以看到ShapeableImageView也没有什么神秘的,不过是ImageView的一个子类而已,但是从效果图来看,在不写shape、不引入三方库的情况下,还是挺容易实现预期效果的,而且扩展性良好。

使用

引入material包

implementation 'com.google.android.material:material:1.2.1'

常规

image
<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp"

    android:src="@mipmap/ic_avatar" />

和ImageView正常使用没有区别。

圆角

image
<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/RoundedStyle" />

<!--ShapeableImageView 圆角-->

<style name="RoundedStyle">

    <item name="cornerFamily">rounded</item>

    <item name="cornerSize">10dp</item>

</style>

没有直接设置圆角的属性,需要用到app:shapeAppearance,后面会说。

cornerFamily 角的处理方式,rounded圆角,cut裁剪。

cornerSize 圆角大小。

<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/CircleStyle" />

<!--ShapeableImageView 圆 -->

<style name="CircleStyle">

    <item name="cornerFamily">rounded</item>

    <item name="cornerSize">50%</item>

</style>

圆角的大小可以用百分比,也可以自己计算,比如宽高100dp,圆角50dp。

描边

image

<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp" 

    android:padding="2dp"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/CircleStyle"

    app:strokeColor="@color/red"

    app:strokeWidth="4dp" />

app:strokeColor 描边颜色。

app:strokeWidth 描边宽度。

注意这里padding的数值是描边宽度的一半,后面会说。

切角

image
<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp" 

    android:padding="2dp"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/CutStyle"

    app:strokeColor="@color/red"

    app:strokeWidth="4dp" />

<!--ShapeableImageView 切角 -->

<style name="CutStyle">

    <item name="cornerFamily">cut</item>

    <item name="cornerSize">10dp</item>

</style>

cornerFamily:cut 处理模式变为裁剪。

菱形

image

<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp" 

    android:padding="2dp"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/RhombusStyle"

    app:strokeColor="@color/red"

    app:strokeWidth="4dp" />

<!--ShapeableImageView 菱形 -->

<style name="RhombusStyle">

    <item name="cornerFamily">cut</item>

    <item name="cornerSize">50%</item>

</style>

同样,裁剪模式下圆角大小也可以计算。

叶子

image
<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp" 

    android:padding="2dp"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/LeafStyle"

    app:strokeColor="@color/red"

    app:strokeWidth="4dp" />

<!--ShapeableImageView 叶子 -->

<style name="LeafStyle">

    <item name="cornerFamily">rounded</item>

    <item name="cornerSizeTopLeft">50%</item>

    <item name="cornerSizeBottomRight">50%</item>

</style>

cornerSizeTopLeft 左上圆角。

cornerSizeBottomRight 右下圆角。

以此类推,左上、左下、右上、右下等。

半圆

image
<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="wrap_content"

    android:layout_margin="10dp" 

    android:padding="2dp"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/SemicircleStyle"

    app:strokeColor="@color/red"

    app:strokeWidth="4dp" />


<!--ShapeableImageView 半圆 -->

<style name="SemicircleStyle">

    <item name="cornerFamily">rounded</item>

    <item name="cornerSizeTopLeft">50%</item>

    <item name="cornerSizeTopRight">50%</item>

</style>

六边形

image
<com.google.android.material.imageview.ShapeableImageView

    android:layout_width="wrap_content"

    android:layout_height="50dp"

    android:layout_margin="10dp" 

    android:padding="2dp"

    android:scaleType="centerCrop"

    android:src="@mipmap/ic_avatar"

    app:shapeAppearance="@style/HexagonStyle"

    app:strokeColor="@color/red"

    app:strokeWidth="4dp" />

<!--ShapeableImageView 六边形 -->

<style name="HexagonStyle">

    <item name="cornerFamily">cut</item>

    <item name="cornerSizeTopLeft">50%</item>

    <item name="cornerSizeTopRight">50%</item>

    <item name="cornerSizeBottomLeft">50%</item>

    <item name="cornerSizeBottomRight">50%</item>

</style>

属性

关于xml属性,我也做了一个整理,属性不多,只有4个。

image

扩展

前面为了整体的排版,埋了几个伏笔,下面来一一解答。

会涉及到源码,但是经过去繁从简,看起来也非常轻松的。

shapeAppearance

Shape appearance overlay style reference for ShapeableImageView.

ShapeableImageView的形状外观覆盖样式参考。

前面可以看到我们设置圆角其实是用的style,那为什么不直接用attrs呢,不是更加直观方便吗,带着疑问来看看源码是怎么处理的。

直接看ShapeableImageView的次构造方法:

public class ShapeableImageView extends AppCompatImageView implements Shapeable {  ...

常规操作,获取自定义属性。

关键的两行代码:

shapeAppearanceModel = ShapeAppearanceModel.builder(context, attrs, defStyle, DEF_STYLE_RES).build();shadowDrawable = new MaterialShapeDrawable(shapeAppearanceModel);

也就是说我们给shapeAppearance设置的style,并不是ShapeableImageView自己来处理的,而是由ShapeAppearanceModel来构建的,然后又交给MaterialShapeDrawable来绘制的。

ShapeAppearanceModel

这个类就厉害了,有点像Flutter中的Decoration,可以构建出花里胡哨的效果。

来看ShapeAppearanceModel部分源码:

public class ShapeableImageView extends AppCompatImageView implements Shapeable {

  ...

  public ShapeableImageView(Context context, @Nullable AttributeSet attrs, int defStyle) {

    super(wrap(context, attrs, defStyle, DEF_STYLE_RES), attrs, defStyle);

    // Ensure we are using the correctly themed context rather than the context that was passed in.

    context = getContext();

    clearPaint = new Paint();

    clearPaint.setAntiAlias(true);

    clearPaint.setColor(Color.WHITE);

    clearPaint.setXfermode(new PorterDuffXfermode(Mode.DST_OUT));

    destination = new RectF();

    maskRect = new RectF();

    maskPath = new Path();

    TypedArray attributes =

        context.obtainStyledAttributes(

            attrs, R.styleable.ShapeableImageView, defStyle, DEF_STYLE_RES);

    strokeColor =

        MaterialResources.getColorStateList(

            context, attributes, R.styleable.ShapeableImageView_strokeColor);

    strokeWidth = attributes.getDimensionPixelSize(R.styleable.ShapeableImageView_strokeWidth, 0);

    borderPaint = new Paint();

    borderPaint.setStyle(Style.STROKE);

    borderPaint.setAntiAlias(true);

    shapeAppearanceModel =

        ShapeAppearanceModel.builder(context, attrs, defStyle, DEF_STYLE_RES).build();

    shadowDrawable = new MaterialShapeDrawable(shapeAppearanceModel);

    if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {

      setOutlineProvider(new OutlineProvider());

    }

  }

}

可以看到有各种边和角的属性,这里注意两个点:

MaterialShapeUtils.createDefaultCornerTreatment() 创建默认角的处理方式。

MaterialShapeUtils.createDefaultEdgeTreatment() 创建默认边的处理方式。

也就意味着,边和角除了默认,是可以自定义的,这就有极大的想象空间了,

比如这样:

image
// 代码设置 角和边val shapeAppearanceModel2 = ShapeAppearanceModel.builder().apply {    setAllCorners(RoundedCornerTreatment())    setAllCornerSizes(50f)    setAllEdges(TriangleEdgeTreatment(50f, false))}.build()val drawable2 = MaterialShapeDrawable(shapeAppearanceModel2).apply {    setTint(ContextCompat.getColor(this@ShapeableImageViewActivity, R.color.colorPrimary))    paintStyle = Paint.Style.FILL_AND_STROKE    strokeWidth = 50f    strokeColor = ContextCompat.getColorStateList(this@ShapeableImageViewActivity, R.color.red)}mBinding.text2.setTextColor(Color.WHITE)mBinding.text2.background = drawable2

再比如这样:

image
// 代码设置 聊天框效果val shapeAppearanceModel3 = ShapeAppearanceModel.builder().apply {    setAllCorners(RoundedCornerTreatment())    setAllCornerSizes(20f)    setRightEdge(object : TriangleEdgeTreatment(20f, false) {        // center 位置 , interpolation 角的大小        override fun getEdgePath(length: Float, center: Float, interpolation: Float, shapePath: ShapePath) {            super.getEdgePath(length, 35f, interpolation, shapePath)        }    })}.build()val drawable3 = MaterialShapeDrawable(shapeAppearanceModel3).apply {    setTint(ContextCompat.getColor(this@ShapeableImageViewActivity, R.color.colorPrimary))    paintStyle = Paint.Style.FILL}(mBinding.text3.parent as ViewGroup).clipChildren = false // 不限制子view在其范围内mBinding.text3.setTextColor(Color.WHITE)mBinding.text3.background = drawable3

MaterialShapeDrawable

源码(有删减):

public class MaterialShapeDrawable extends Drawable implements TintAwareDrawable, Shapeable {...  @Override  public void draw(@NonNull Canvas canvas) {    fillPaint.setColorFilter(tintFilter);    final int prevAlpha = fillPaint.getAlpha();    fillPaint.setAlpha(modulateAlpha(prevAlpha, drawableState.alpha));    strokePaint.setColorFilter(strokeTintFilter);    strokePaint.setStrokeWidth(drawableState.strokeWidth);    final int prevStrokeAlpha = strokePaint.getAlpha();    strokePaint.setAlpha(modulateAlpha(prevStrokeAlpha, drawableState.alpha));    if (pathDirty) {      calculateStrokePath();      calculatePath(getBoundsAsRectF(), path);      pathDirty = false;    }    maybeDrawCompatShadow(canvas);    if (hasFill()) {      drawFillShape(canvas);    }    if (hasStroke()) {      drawStrokeShape(canvas);    }...  static final class MaterialShapeDrawableState extends ConstantState {    ...    public MaterialShapeDrawableState(@NonNull MaterialShapeDrawableState orig) {      shapeAppearanceModel = orig.shapeAppearanceModel;      elevationOverlayProvider = orig.elevationOverlayProvider;      strokeWidth = orig.strokeWidth;      colorFilter = orig.colorFilter;      fillColor = orig.fillColor;      strokeColor = orig.strokeColor;      tintMode = orig.tintMode;      tintList = orig.tintList;      alpha = orig.alpha;      scale = orig.scale;      shadowCompatOffset = orig.shadowCompatOffset;      shadowCompatMode = orig.shadowCompatMode;      useTintColorForShadow = orig.useTintColorForShadow;      interpolation = orig.interpolation;      parentAbsoluteElevation = orig.parentAbsoluteElevation;      elevation = orig.elevation;      translationZ = orig.translationZ;      shadowCompatRadius = orig.shadowCompatRadius;      shadowCompatRotation = orig.shadowCompatRotation;      strokeTintList = orig.strokeTintList;      paintStyle = orig.paintStyle;      if (orig.padding != null) {        padding = new Rect(orig.padding);      }    }...  }...}

没什么特别的,你只需要知道除了可以设置描边之外,还可以设置背景、阴影等其他属性。

说明

ShapeAppearanceModel只能是实现Shapeable接口的View才可以设置,比如Chip、MaterialButtom等。

而MaterialShapeDrawable其实就是Drawable,是所有View都可以设置的。

描边问题

这里借github一张图:

image

又是自定义view的常规操作,有一半画笔是在边界外面的,所以需要设置padding为strokeWidth的一半。

默认圆角问题

有细心的同学会发现啊,第一个常规的ShapeableImageView还是有一点圆角的,没错,属于默认的,跟踪一下源码来看一下:

<style name="Widget.MaterialComponents.ShapeableImageView" parent="android:Widget">    <item name="strokeColor">@color/material_on_surface_stroke</item>    <item name="shapeAppearance">?attr/shapeAppearanceMediumComponent</item></style>

第一个是颜色,很明显不是我们要找的,继续看shapeAppearanceMediumComponent

<attr format="reference" name="shapeAppearanceMediumComponent"/>

只是一个简单的属性,继续查找关联引用。

<item name="shapeAppearanceMediumComponent">  @style/ShapeAppearance.MaterialComponents.MediumComponent</item>

又引用了一个style,继续看ShapeAppearance.MaterialComponents.MediumComponent这个style。

<style name="ShapeAppearance.MaterialComponents.MediumComponent">    <item name="cornerSize">@dimen/mtrl_shape_corner_size_medium_component</item></style>

哦豁,看到了熟悉的属性cornerSize,藏的还挺深,继续看看数值是多少。

<dimen name="mtrl_shape_corner_size_medium_component">4dp</dimen>

默认4dp。

那如果不想要这个圆角怎么办呢,可以学习源码仿写一个,不过上面也看到了,有点绕,不如直接写个style搞定:

<!--ShapeableImageView 去圆角--><style name="Corner0Style">    <item name="cornerSize">0dp</item></style>

然后引用

app:shapeAppearance="@style/Corner0Style"

效果:

image

ok,到这里就差不多了,虽然还有很多相关知识点没有提及,但是也不少了,不如自己去尝试一番,慢慢消化。

作者:10块钱new一个对象
链接:https://www.jianshu.com/p/be5482ed5c22
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容