我正在实现自定义ViewGroup,它具有重叠的ImageViews。 我使用GlideApp加载图像。问题是某些图像被裁剪了一些(在左侧可见),我无法防止这种情况。被裁剪的可绘制对象是Vector可绘制对象,它们的mDrawableWidth和mDrawableHeight大于ViewGroup的高度。我认为可以缩放图像以适合视图尺寸(mScaleType = FIT_CENTER)。
class OverlappingImageViewGroup : ViewGroup {
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthSize: Int = getDefaultSize(0, widthMeasureSpec)
val heightSize: Int = getDefaultSize(0, heightMeasureSpec)
val majorDimension = Math.min(widthSize, heightSize)
//Measure all child views
val childSpec = MeasureSpec.makeMeasureSpec(majorDimension, MeasureSpec.EXACTLY)
measureChildren(childSpec, childSpec)
//MUST call this to save our own dimensions
setMeasuredDimension(majorDimension, majorDimension)
}
override fun onLayout(changed: Boolean,
leftRelativeToParent: Int,
topRelativeToParent: Int,
rightRelativeToParent: Int,
bottomRelativeToParent: Int) {
val percentOverlap = 0.8f
if (childCount > 0) {
for (i in 0 until childCount) {
val child = getChildAt(i)
val childWidth = child.measuredWidth
val topBound = 0 /* there is just one row */
if (i == 0) {
child.layout(0, topBound, childWidth, childWidth)
} else {
val leftBound = i * percentOverlap * childWidth
child.layout(
leftBound.toInt(),
topBound,
leftBound.toInt() + childWidth,
topBound + childWidth)
}
}
}
}
}
以编程方式创建ImageView:
val context = holder.rootView.context
val imageView: ImageView = ImageView(context)
GlideApp.with(context)
.load(imageUrl)
.placeholder(userPlaceholder)
.fallback(userPlaceholder)
.error(userPlaceholder)
.transform(CircleWithBorderTransform())
.into(imageView)
holder.membersIcons.addView(imageView)
滑行变换
override fun transform(pool: BitmapPool, source: Bitmap, outWidth: Int, outHeight: Int): Bitmap {
val width = source.width
val height = source.height
val canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
val paint = Paint()
paint.isAntiAlias = true
paint.shader = shader
val canvas = Canvas(canvasBitmap)
val radius = if (width > height) height.toFloat() / 2f else width.toFloat() / 2f
canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), radius, paint)
//border around the image
paint.shader = null
paint.style = Paint.Style.STROKE
paint.strokeWidth = 2f
paint.color = Color.WHITE
canvas.drawCircle((width / 2).toFloat(), (height / 2).toFloat(), radius, paint)
return canvasBitmap
}