span从入门到精通2 自定义drawable

2024-05-29 00:32

本文主要是介绍span从入门到精通2 自定义drawable,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

分析昨天的博客 span从入门到精通 第三方工具类GifDrawable 发现有个知识点有必要先梳理下要不大家可能看着博客都是懵逼的,这个知识点就是自定义drawable。
看看效果吧
drawable画圆

图片
首先我们先分析下源码里面drawable 是怎么被调用的我们先看看view类 的setBackgroundDrawable 这个方法

public void setBackgroundDrawable(Drawable background) {computeOpaqueFlags();if (background == mBackground) {return;}boolean requestLayout = false;mBackgroundResource = 0;/** Regardless of whether we're setting a new background or not, we want* to clear the previous drawable. setVisible first while we still have the callback set.*/if (mBackground != null) {if (isAttachedToWindow()) {mBackground.setVisible(false, false);}mBackground.setCallback(null);unscheduleDrawable(mBackground);}if (background != null) {Rect padding = sThreadLocal.get();if (padding == null) {padding = new Rect();sThreadLocal.set(padding);}resetResolvedDrawablesInternal();background.setLayoutDirection(getLayoutDirection());if (background.getPadding(padding)) {resetResolvedPaddingInternal();switch (background.getLayoutDirection()) {case LAYOUT_DIRECTION_RTL:mUserPaddingLeftInitial = padding.right;mUserPaddingRightInitial = padding.left;internalSetPadding(padding.right, padding.top, padding.left, padding.bottom);break;case LAYOUT_DIRECTION_LTR:default:mUserPaddingLeftInitial = padding.left;mUserPaddingRightInitial = padding.right;internalSetPadding(padding.left, padding.top, padding.right, padding.bottom);}mLeftPaddingDefined = false;mRightPaddingDefined = false;}// Compare the minimum sizes of the old Drawable and the new.  If there isn't an old or// if it has a different minimum size, we should layout againif (mBackground == null|| mBackground.getMinimumHeight() != background.getMinimumHeight()|| mBackground.getMinimumWidth() != background.getMinimumWidth()) {requestLayout = true;}// Set mBackground before we set this as the callback and start making other// background drawable state change calls. In particular, the setVisible call below// can result in drawables attempting to start animations or otherwise invalidate,// which requires the view set as the callback (us) to recognize the drawable as// belonging to it as per verifyDrawable.mBackground = background;if (background.isStateful()) {background.setState(getDrawableState());}if (isAttachedToWindow()) {background.setVisible(getWindowVisibility() == VISIBLE && isShown(), false);}applyBackgroundTint();// Set callback last, since the view may still be initializing.background.setCallback(this);if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) {mPrivateFlags &= ~PFLAG_SKIP_DRAW;requestLayout = true;}} else {/* Remove the background */mBackground = null;if ((mViewFlags & WILL_NOT_DRAW) != 0&& (mDefaultFocusHighlight == null)&& (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) {mPrivateFlags |= PFLAG_SKIP_DRAW;}/** When the background is set, we try to apply its padding to this* View. When the background is removed, we don't touch this View's* padding. This is noted in the Javadocs. Hence, we don't need to* requestLayout(), the invalidate() below is sufficient.*/// The old background's minimum size could have affected this// View's layout, so let's requestLayoutrequestLayout = true;}computeOpaqueFlags();if (requestLayout) {requestLayout();}mBackgroundSizeChanged = true;invalidate(true);invalidateOutline();}

这里面的意思大致分析一下就是首先判断设置的drawable是否跟以前的一样如果一样则不需要重新设置,如果旧的background不为空则清理下旧的background的数据,之后设置background的state,visible,callback等属性,最终调用requestLayout这个方法重新绘制布局也就是会走layout跟draw等方法,系统会在draw方法里面调用drawBackground这个处理我们来看drawBackground这个方法里面做了些什么处理

  private void drawBackground(Canvas canvas) {final Drawable background = mBackground;if (background == null) {return;}setBackgroundBounds();// Attempt to use a display list if requested.if (canvas.isHardwareAccelerated() && mAttachInfo != null&& mAttachInfo.mThreadedRenderer != null) {mBackgroundRenderNode = getDrawableRenderNode(background, mBackgroundRenderNode);final RenderNode renderNode = mBackgroundRenderNode;if (renderNode != null && renderNode.isValid()) {setBackgroundRenderNodeProperties(renderNode);((DisplayListCanvas) canvas).drawRenderNode(renderNode);return;}}final int scrollX = mScrollX;final int scrollY = mScrollY;if ((scrollX | scrollY) == 0) {background.draw(canvas);} else {canvas.translate(scrollX, scrollY);background.draw(canvas);canvas.translate(-scrollX, -scrollY);}}

这里我们只关注一句话background.draw(canvas);即当我们在绘制内容之前会调用drawable的draw方法绘制背景,因此drawable里面的draw方法是一个十分关键的代码它会将我们需要的图片文字等内容绘制到界面中。好了源码先分析到这里我们还是先看看基本使用吧。
好了废话先不多说了先看实现代码吧我们首先定义一个drawable类。(一个极其简单的类)

public class TestDrawable extends Drawable {private Paint paint;//画笔private int mWidth = 300;//图片宽与高的最小值public TestDrawable() {paint = new Paint();paint.setAntiAlias(true);paint.setColor(Color.YELLOW);paint.setStyle(Paint.Style.FILL);}public void setmWidth(int width){this.mWidth=width;invalidateSelf();//更新设置}@Overridepublic void draw(@NonNull Canvas canvas) {canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2, paint);}@Overridepublic void setAlpha(int i) {paint.setAlpha(i);invalidateSelf();//更新设置}@Overridepublic int getIntrinsicHeight() {return mWidth;}@Overridepublic int getIntrinsicWidth() {return mWidth;}@Overridepublic void setColorFilter(@Nullable ColorFilter colorFilter) {paint.setColorFilter(colorFilter);invalidateSelf();//更行设置}@Overridepublic int getOpacity() {return PixelFormat.TRANSLUCENT;}}

看到了吧是不是有一种恍然大明白的感觉
我们的设置极其简单许多都是固定模式化的东西
1.初始化paint这个不用我多说了吧不知道的自觉面壁去
2.setAlpha中设置paint的alpha
3.getIntrinsicHeight getIntrinsicWidth当布局为wrap_content的时候我们要画的内容的宽高
4.setColorFilter调用paint的setColorFilter处理
5.getOpacity一班返回PixelFormat.TRANSLUCENT即可
6.最最核心的处理draw方法这里我们画了一个圆大家也可以画其他图形,图片等处理
7.额外添加一个方法setmWidth重新定义控件的宽度这里要注意了invalidateSelf这个方法调用会重新绘制该布局
这下明白了吧下面就是外部的调用

TestDrawable drawable = new TestDrawable();
ImageView iv_main = findViewById(R.id.iv_main);
iv_main.setImageDrawable(drawable);
drawable.setmWidth(50);

一句iv_main.setImageDrawable将我们画的drawable中的圆画到了界面上是不是很神奇
当然大家如果需要做动画的话可以调用invalidateSelf不断改变我们画的内容

如果大家还是不太明白可以看看画图片是怎么处理的代码如下

public class TestDrawable extends Drawable {private Paint paint;//画笔private int mWidth;//图片宽与高的最小值private Bitmap bitmap;//位图public TestDrawable(Context context, int resID) {this(BitmapFactory.decodeResource(context.getResources(), resID));}public TestDrawable(Bitmap bitmap) {this.bitmap = bitmap;paint = new Paint();paint.setAntiAlias(true);//抗锯齿paint.setDither(true);//抖动,不同屏幕尺的使用保证图片质量///位图渲染器BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);paint.setShader(bitmapShader);mWidth = Math.min(bitmap.getWidth(), bitmap.getHeight());}@Overridepublic void draw(@NonNull Canvas canvas) {canvas.drawCircle(mWidth / 2, mWidth / 2, mWidth / 2, paint);}@Overridepublic void setAlpha(int i) {paint.setAlpha(i);invalidateSelf();//更新设置}@Overridepublic int getIntrinsicHeight() {return bitmap.getHeight();}@Overridepublic int getIntrinsicWidth() {return bitmap.getWidth();}@Overridepublic void setColorFilter(@Nullable ColorFilter colorFilter) {paint.setColorFilter(colorFilter);invalidateSelf();//更行设置}@Overridepublic int getOpacity() {return PixelFormat.TRANSLUCENT;}}

代码也不多希望大家看完博客后能对drawable有个更深入的认识

github链接点击这里

这篇关于span从入门到精通2 自定义drawable的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1012134

相关文章

Spring Boot + MyBatis Plus 高效开发实战从入门到进阶优化(推荐)

《SpringBoot+MyBatisPlus高效开发实战从入门到进阶优化(推荐)》本文将详细介绍SpringBoot+MyBatisPlus的完整开发流程,并深入剖析分页查询、批量操作、动... 目录Spring Boot + MyBATis Plus 高效开发实战:从入门到进阶优化1. MyBatis

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

基于Spring实现自定义错误信息返回详解

《基于Spring实现自定义错误信息返回详解》这篇文章主要为大家详细介绍了如何基于Spring实现自定义错误信息返回效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录背景目标实现产出背景Spring 提供了 @RestConChina编程trollerAdvice 用来实现 HTT

SpringSecurity 认证、注销、权限控制功能(注销、记住密码、自定义登入页)

《SpringSecurity认证、注销、权限控制功能(注销、记住密码、自定义登入页)》SpringSecurity是一个强大的Java框架,用于保护应用程序的安全性,它提供了一套全面的安全解决方案... 目录简介认识Spring Security“认证”(Authentication)“授权” (Auth

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

SpringBoot自定义注解如何解决公共字段填充问题

《SpringBoot自定义注解如何解决公共字段填充问题》本文介绍了在系统开发中,如何使用AOP切面编程实现公共字段自动填充的功能,从而简化代码,通过自定义注解和切面类,可以统一处理创建时间和修改时间... 目录1.1 问题分析1.2 实现思路1.3 代码开发1.3.1 步骤一1.3.2 步骤二1.3.3

dubbo3 filter(过滤器)如何自定义过滤器

《dubbo3filter(过滤器)如何自定义过滤器》dubbo3filter(过滤器)类似于javaweb中的filter和springmvc中的intercaptor,用于在请求发送前或到达前进... 目录dubbo3 filter(过滤器)简介dubbo 过滤器运行时机自定义 filter第一种 @A

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...