我们自定义View的目的是为了针对我们的工程需要,完成一些内置View不能实现或者实现起来很麻烦的功能。其中我们需要复写onMeasure()
, onLayout()
以及onDraw()
。
接下来我们将通过自定义View实现类似于微信头像的效果。
首先我们需要继承View或者View的子类并完成构造函数。比如我们在这里自定义一个CustomImageView
:
// 主构造函数 第三个参数为默认Style
class CustomImageView(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) :
androidx.appcompat.widget.AppCompatImageView(context, attributeSet, defStyleAttr) {
// 次构造函数 第二个参数为自定义属性集合,用与取出XML配置中的自定义属性
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
// 次构造函数 参数为上下文对象
constructor(context: Context) : this(context, null)
}
onMeasure
自定义View中有一项很重要的工作就是测量View的大小,这是由于我们在xml配置中不仅仅会使用具体的精确值,还有可能会使用match_parent
以及wrap_content
。其中,match_parent
是设置子视图尺寸为占满父视图;wrap_content
是设置子视图尺寸为包裹着自身内容。由于这两种设置没有设置具体的大小,因此我们需要在自定义的View中复写具体的逻辑。此外,若我们对View的形状有特别的要求,比如圆形或者正方形等,即使在配置中指定具体的数值也无法满足我们的要求,这种情况也需要复写逻辑。
我们接下来通过复写onMeasure
方法将View变成一个正方形,方便后续在onDraw
中画圆。
在复写方法之前我们还需要了解一个类MeasureSpec
MeasureSpec
MeasureSpec
类非常简单,加上注释也不过一百多行。他的主要功能就是将View测量的数据通过一个整型保存下来,其中不光有尺寸信息还包括测量模式。主要思想就是一个Int有32个字节,将其前面两个字节用来保存三种测量模式,后面30位来保存尺寸信息。
// 用于将测量模式的左移操作
private static final int MODE_SHIFT = 30;
// 最高两位都是1的整型,方便取前2位或后30位的值
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
/**
* 测量模式1: 父视图对子视图没有限制,子视图可以是任意大小
*/
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
/**
* 测量模式2: 父视图对子视图有确定的大小要求
*/
public static final int EXACTLY = 1 << MODE_SHIFT;
/**
* 测量模式3: 子视图可以根据需要任意大,直到指定大小。
*/
public static final int AT_MOST = 2 << MODE_SHIFT;
@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
相应的存取方法也已经封装好了:
public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,@MeasureSpecMode int mode) {
// sUseBrokenMakeMeasureSpec为true代表使用旧方法,与else的计算结果是一致的。
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
我们继续回归复写onMeasure
方法上,由于我们想要一个正方形即长等于宽,因此我们需要将测量所得的长宽信息取出后设置为相同的值后再保存起来。
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
// 取长宽的最小值作为圆的半径,即此时仍为长方形的长宽
radius = min(getSize(radius, widthMeasureSpec), getSize(radius, heightMeasureSpec))
// 此函数只可以在onMeasure中使用,可以为View设置长宽
setMeasuredDimension(radius, radius)
}
private fun getSize(defaultSize: Int, measureSpec: Int): Int {
val measureMode = MeasureSpec.getMode(measureSpec)
val measureSize = MeasureSpec.getSize(measureSpec)
// 当测量模式为精确值或最大值模式时,我们取测量值,否则使用默认值
return when (measureMode) {
MeasureSpec.EXACTLY, MeasureSpec.AT_MOST -> measureSize
MeasureSpec.UNSPECIFIED -> defaultSize
else -> defaultSize
}
}
onDraw
由于我们需要View能显示圆形的照片,而普通的ImageView是矩形的,因此我们必然要复写onDraw
方法。
// 设置传输模式,传输模式定义了源像素与目标像素的组合规则。
// PorterDuff.Mode.SRC_IN 这种模式,两个绘制的效果叠加后取两者的交集部分并展现后图
// 此处为显示圆形图片的关键地方
private val mXfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
// 将原背景透明度设为0
background.alpha = 0
canvas?.drawBitmap(createCircleBitmap(mProfilePhoto, radius), 0F, 0F, null)
}
/**
* 显示圆形图片的关键方法
* src: 需要显示的图片,需转成位图
* radius: 圆形的半径
*/
private fun createCircleBitmap(src: Bitmap, radius: Int) : Bitmap {
mPaint.reset()
// createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight,boolean filter)
// 可以根据原始位图以及给定的长宽相等的位图,若原图满足要求则返回原图
// src 原图
// dstWidth 目标宽度
// dstHeight 目标长度
// filter 缩放位图时是否使用过滤,过滤会损失部分性能并显著提高图像质量
val srcScaled = Bitmap.createScaledBitmap(src, radius, radius, true)
// createBitmap(@Nullable DisplayMetrics display, int width,
// int height, @NonNull Config config)
// 生成指定宽度和高度的位图
// config: 创建位图的设置 Bitmap.Config.ARGB_8888:可以提供最好的位图质量
val target = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888)
// 指定画布要绘制的位图
mCanvas.setBitmap(target)
// 画圆
mCanvas.drawCircle(radius / 2F, radius / 2F, radius / 2F, mPaint)
mPaint.xfermode = mXfermode
// 由于我们使用PorterDuff.Mode.SRC_IN 这种模式,并且先绘制了一个圆形
// 因此我们再绘制位图就会显示成圆形的图片
mCanvas.drawBitmap(srcScaled, 0F, 0F, mPaint)
return target
}
一个合格的自定义View应该也要允许用户自定义一些属性值,只有当用户不指定时,我们才使用我们的默认值。首先我们需要在res/values/styles.xml
文件中(若无文件,则需要新建)声明我们的自定义属性。格式如下:
<resources>
<!-- 声明属性集合的名称,官方建议与类名相同 -->
<declare-styleable name="CustomImageView">
<!-- 声明半径属性,名称为radius,格式为尺寸类型(dp等) -->
<attr name="radius" format="dimension" />
<!-- 声明引用图片,名称为resID,格式为引用类型 -->
<attr name="resID" format="reference" />
</declare-styleable>
</resources>
随后即可在布局文件中使用自定义属性:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#dd78dd98"
tools:context=".MainActivity">
<com.example.customviewdemo.CustomVerticalLinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/black">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/test_button"
android:textSize="25sp"
android:textAllCaps="false" />
<com.example.customviewdemo.CustomImageView
android:layout_width="200dp"
android:layout_height="200dp"
custom:radius="300dp"
custom:resID="@drawable/profile" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/test_button"
android:textSize="40sp"
android:textAllCaps="false" />
</com.example.customviewdemo.CustomVerticalLinearLayout>
</LinearLayout>
CustomVerticalLinearLayout
是我们后续会用到的自定义ViewGroup,可以先不用管。而自定义属性custom:radius="300dp"
中的custom
是命名空间,需要在父容器指定,可以为任意值,如这里的xmlns:custom="http://schemas.android.com/apk/res-auto"
,其中"http://schemas.android.com/apk/res-auto"
是固定格式。
最后我们需要在构造函数中取出相应值。
init {
// 取得属性值数组
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CustomImageView)
// 获取尺寸属性
radius = typedArray.getDimensionPixelSize(R.styleable.CustomImageView_radius, 200)
// 获得引用属性
mProfilePhoto = BitmapFactory.decodeResource(resources , typedArray.getResourceId(R.styleable.CustomImageView_resID, R.drawable.profile))
// 最后需要回收数组
typedArray.recycle()
}
总体代码如下,布局文件以及style.xml已经在上文中给出。
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val viewBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
}
}
class CustomImageView(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) :
androidx.appcompat.widget.AppCompatImageView(context, attributeSet, defStyleAttr) {
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context) : this(context, null)
private val mPaint = Paint()
private var mProfilePhoto = BitmapFactory.decodeResource(resources, R.drawable.profile)
private val mCanvas = Canvas()
private var radius = 200
init {
val typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.CustomImageView)
radius = typedArray.getDimensionPixelSize(R.styleable.CustomImageView_radius, 200)
mProfilePhoto = BitmapFactory.decodeResource(resources
, typedArray.getResourceId(R.styleable.CustomImageView_resID, R.drawable.profile))
typedArray.recycle()
}
companion object {
const val TAG = "CustomImageView"
private val mXfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
radius = min(getSize(radius, widthMeasureSpec), getSize(radius, heightMeasureSpec))
setMeasuredDimension(radius, radius)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
background.alpha = 0
canvas?.drawBitmap(createCircleBitmap(mProfilePhoto, radius), 0F, 0F, null)
}
private fun createCircleBitmap(src: Bitmap, radius: Int) : Bitmap {
mPaint.reset()
val srcScaled = Bitmap.createScaledBitmap(src, radius, radius, true)
val target = Bitmap.createBitmap(radius, radius, Bitmap.Config.ARGB_8888)
mCanvas.setBitmap(target)
mCanvas.drawCircle(radius / 2F, radius / 2F, radius / 2F, mPaint)
mPaint.xfermode = mXfermode
mCanvas.drawBitmap(srcScaled, 0F, 0F, mPaint)
return target
}
private fun getSize(defaultSize: Int, measureSpec: Int): Int {
val measureMode = MeasureSpec.getMode(measureSpec)
val measureSize = MeasureSpec.getSize(measureSpec)
return when (measureMode) {
MeasureSpec.EXACTLY, MeasureSpec.AT_MOST -> measureSize
MeasureSpec.UNSPECIFIED -> defaultSize
else -> defaultSize
}
}
}
自定义ViewGroup相比于自定义View会更加复杂一点,因为它不仅涉及到自身的测量,摆放以及绘制,还需要安排好子元素的测量,摆放以及绘制。但是ViewGroup本质上还是一个View,它继承自View,因此它也只需像自定义View一样重写onMeasure()
, onLayout()
以及onDraw()
即可。
接下来我们通过自定义ViewGroup实现类似LinearLayout的效果
onMeasure()
由于我们的ViewGroup是一个容器,因此我们在计算尺寸的时候理所当然需要知道所有子视图的大小。在这里我们的自定义ViewGroup是模仿垂直布局的LinearLayout。
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
// 测量所有子元视图
measureChildren(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
if (childCount == 0) {
// 无子视图,没有必要展示
setMeasuredDimension(0, 0)
} else {
if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
// 对子视图的宽高都无限制,则高度为所有子视图的高度之和,宽度为子视图中的最大宽度
setMeasuredDimension(children.maxOf {
it.measuredWidth }, children.sumOf {
it.measuredHeight })
} else if (widthMode == MeasureSpec.AT_MOST) {
// 对子视图宽度无限制,则高度为自身的测量值,宽度为子视图中的最大宽度
setMeasuredDimension(children.maxOf {
it.measuredWidth }, height)
} else if (heightMode == MeasureSpec.AT_MOST) {
// 对子视图高度无限制,则高度为所有子视图的高度之和,宽度为自身的测量值
setMeasuredDimension(width, children.sumOf {
it.measuredHeight })
}
}
}
onLayout()
onLayout()
只需按照顺序依次摆放每个子视图即可,其中子视图的上下位置位置可以通过上方所有子视图的累加高度以及自身高度计算得到;左右位置可以通过子元素自身宽度计算得到。
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
// 子视图的起始高度
var curHeight = 0
for (child in children) {
// 摆放当前子视图的位置
child.layout(l, t+curHeight, l+child.measuredWidth, t+curHeight+child.measuredHeight)
// 累加子视图高度
curHeight += child.measuredHeight
}
}
总体代码如下,其余代码已经在上文中给出。
class CustomVerticalLinearLayout(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)
: ViewGroup(context, attributeSet, defStyleAttr, defStyleRes) {
constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int)
: this(context, attributeSet, defStyleAttr, 0)
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context) : this(context, null)
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
var curHeight = 0
for (child in children) {
child.layout(l, t+curHeight, l+child.measuredWidth, t+curHeight+child.measuredHeight)
curHeight += child.measuredHeight
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
measureChildren(widthMeasureSpec, heightMeasureSpec)
val width = MeasureSpec.getSize(widthMeasureSpec)
val widthMode = MeasureSpec.getMode(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
val heightMode = MeasureSpec.getMode(heightMeasureSpec)
if (childCount == 0) {
setMeasuredDimension(0, 0)
} else {
if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(children.maxOf {
it.measuredWidth }, children.sumOf {
it.measuredHeight })
} else if (widthMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(children.maxOf {
it.measuredWidth }, height)
} else if (heightMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(width, children.sumOf {
it.measuredHeight })
}
}
}
}
文章浏览阅读185次。安装好robotframework库后,跟之前文章介绍的BuiltIn库一样BuiltIn库使用介绍,在“python安装目录\Lib\site-packages\robot\libraries”中有一个常用库Collections.py,主要用于操作列表和字典。打开客户端ride后,BuiltIn模块是默认导入,可直接使用,而其他模块或者第三方模块/包都需要import才能被使用。我们可以在测试套件和resource文件中导入这些模块或者包,两者导入的方式是一样的。_robotframe的get match count的用法
文章浏览阅读4.9k次。如何使用slider控件绑定编辑框,使编辑框的内容随slider滑块的滑动而改变数值就像下面的图片上一样首先在主对话框上拖入一个slider控件,和编辑框控件。分别为两个控件绑定一个变量。为slider控件绑定一个控制事件 NM_COSTUMDRAW.然后在主对话框初始化函数中添加以下代码 m_slider.SetRange(0, 40); m_slider.SetLineSize..._access 窗体中的slider 控件
文章浏览阅读316次。基于Java的文章发布系统设计与实现的性能评估是对系统在特定工作负载下的响应速度和资源利用率进行评估和分析,旨在验证系统是否能够满足用户在实际使用中的性能需求。1、并发性能评估:并发性能是指系统在多用户同时访问的情况下的表现。通过模拟多个用户同时进行操作,评估系统的并发性能。可以观察系统是否能够正确处理并发请求,同时保持较好的响应速度。通过增加并发用户数,可以评估系统的并发处理能力和性能瓶颈。在本系统的性能测试中,通过不断增加并发用户数,测试系统的并发处理能力和性能瓶颈。_java实现发布任务
文章浏览阅读364次。我们尝试在docker下配置webgoat-7.1docker有windows版本,但是只有window 10专业版可以使用,而且会打开hype-v选项,这会导致vmware和vbox虚拟机无法正常使用,故而尝试在fedora虚拟机中安装docker1.安装vm虚拟机(或者vbox虚拟机)和fdora环境,在此便不再讲述。这里我们使用的是fedora31环境。2.安装dockerfedora环境下无法使用dnf直接安装docker-ce,要么找不到docker-ce,要么缺少依赖。所以我们先下载3_fedora docker-ce-cli
文章浏览阅读223次。第二章 Learning an expandable EMR-based medical knowledge network to enhance clinical diagnosis2.1 核心问题科学问题智能诊断系统只考虑患者特征并利用分类模型进行诊断,模型对外表现为黑盒,不具有可信度。利用知识图谱减少对训练数据的依赖,提高诊断模型的鲁棒性。以往知识图谱的可靠性受限于数据库的规模以及包含的医学短语。从文本中识别并抽取特征的模型需要大量训练数据,且不具有可扩展性,无法针对新名词及知识进行_clinical information extraction applications: a literature review
文章浏览阅读802次,点赞34次,收藏10次。1、JS是一门单线程语言, 运行在浏览器渲染主线程中,且渲染主线程只有一个(渲染主线程承担着诸多工作如:页面渲染,JS执行等)2、如果同步执行可能会造成主线程阻塞,从而导致消息队列中其他任务无法得到执行,(影响: 1、浪费主线程时间;2、页面无法及时更新造成页面卡顿)3、具体做法;当某些任务发生时(计时器、网络、事件监听)主线程将把任务分配给其他线程,自身结束任务执行,转而执行后续代码。当其他线程完成时,将事先传递的回调函数包装成任务加装在消息队列末尾,等待主线程执行。_浏览器 事件循环与渲染
文章浏览阅读71次。当然,您现在已经听说过Meltdown。 这是一个硬件漏洞,它允许未经授权的进程访问特权内存。 它影响自1995年以来生产的英特尔处理器。以下是一些详细信息: https : //en.wikipedia.org/…/Meltdown_(security_vulnerability) 解决此问题的唯一有效方法是对操作系统的内核(Linux,Windows,macOS)应用补丁,这将显着增加系统..._meltdown预防
文章浏览阅读2.7k次。本人现在在学习C++编程,经过一段时间也积累收藏了很多自己认为不错的文章,其中也有自己写的一些,现整理出来方便大家使用!并希望大家指正和建议和交流!希望对大家有帮助!咱们一起努力进步,因为我还是编程的一般水平!首先是C/C++忠告(转载)估计大家都看过:1.把C++当成一门新的语言学习(和C没啥关系!真的。); 2.看《Thinking In C++》,不要看《C+_c++程序设计技术推文
文章浏览阅读1.3k次。Android studio:使用git进行版本回退最近使用Android studio 进行版本回退,出现的一些问题和大家分享一下首先找到Android studio中 VCS–GIT–Reset HEADReset Type下拉Reset Type(重置类型) 里面有三种类型,Mixed、Soft、Hard这三种类型不要乱选!!!mixed:此为默认方式,不带任何参数的git ..._android studio git回退
文章浏览阅读2.3k次。本文转自http://eslxf.blog.51cto.com/918801/213825 1.6 wpcap.dll中相应函数接口的实现wpcap.dll主要依赖于packet.dll导出的PacketSendPacket函数与PacketSendPackets函数分别实现单个数据包发送与发送队列方式的发送。下面分析wpcap.dll中相应函数的内部实现。1._linux pcap_sendpacket() 返回-1
文章浏览阅读8.3k次。转载于:http://www.cnblogs.com/earl-yongchang/p/5609102.html重写angularjs的ng-click事件 代码为:app.config(['$provide', function ($provide) { $provide.decorator('ngCli_angular防重提
文章浏览阅读629次,点赞9次,收藏9次。在json序列化/反序列化时将java bean中使用了该注解的属性忽略掉_@jsonignore