自定义view展示六边形图片

  • 效果如下:
效果图.jpg

实现思路:

用canvas.drawPath(path,paint)先绘制一个六边形的形状。 然后在结合BitmapShader方法将

我们的图片bitmap设置给画笔就ok了。

例子:

val bitmapShader = BitmapShader(Bitamp, Shader.TileMode.MIRROR, Shader.TileMode.MIRROR)
//计算缩放比例
var mScale = sourceWidth.toFloat() / Bitamp.width.toFloat()
val matrix = Matrix()
matrix.setScale(mScale, mScale)
bitmapShader.setLocalMatrix(matrix)
var mPaint = Paint()
mPaint.shader = bitmapShader
Canvas.drawPath(Path, mPaint)

第一步测量view的宽高

我们的六边形是一个正六边形 所以宽高要一样。

这里还有个知识点:由于画笔具有宽度,所以我们在设定view的宽高的时候要考虑到画笔宽度的那部分值,不然就会出现我们画出来的view有一部分会显示不出来的情况。

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(handleMeasure(widthMeasureSpec), handleMeasure(heightMeasureSpec))
    }
/**
  * 处理宽高
  */
private fun handleMeasure(measureSpec: Int): Int {
        var specMode: Int = MeasureSpec.getMode(measureSpec)
        var specSize: Int = MeasureSpec.getSize(measureSpec)
        var result = 100
        result = when (specMode) {
            MeasureSpec.EXACTLY -> {
                specSize
            }
            else -> {
                min(result, specSize)
            }
        }
        parentWidth = result + sixStroke.toInt() * 2 //这里又加了个 sixStroke * 2 就是考虑到了画笔的宽度
        return parentWidth
    }

到这里我们的view的大小就确定好了。

第二步绘制一个六边形的形状

override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
            var circlePointX = parentWidth / 2
            var radian60 = 60 * Math.PI / 180
            var xLength = circlePointX * sin(radian60)
            var yLength = circlePointX * cos(radian60)
            path.reset()
            path.moveTo(circlePointX.toFloat(), sixStroke / 2)
            path.lineTo(circlePointX.toFloat() + xLength.toFloat(), yLength.toFloat())
            path.lineTo(
                    circlePointX.toFloat() + xLength.toFloat(),
                    circlePointX + yLength.toFloat()
            )
            path.lineTo(circlePointX.toFloat(), parentWidth.toFloat() - sixStroke / 2)
            path.lineTo(
                    circlePointX.toFloat() - xLength.toFloat(),
                    circlePointX + yLength.toFloat()
            )
            path.lineTo(circlePointX.toFloat() - xLength.toFloat(), yLength.toFloat())
            path.close()
            canvas.drawPath(path, mPaint)
        }
    }

至此一个六边形就绘制完毕。

第三步优化我们的六边形 让他兼顾展示网络图片的功能。

先引入我们的Glide图片加载框架:

   /**
     * glide图片加载
     */
    api "com.github.bumptech.glide:glide:4.11.0"
    annotationProcessor "com.github.bumptech.glide:compiler:2.0"

自定义Glide加载图片的transform方法:

class PentagonaltTransform(val width: Float) : BitmapTransformation() {
    val path = Path()
    lateinit var mCanvas: Canvas
    val mPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            color = Color.RED
            strokeWidth = 10f
            strokeCap = Paint.Cap.ROUND
            pathEffect = CornerPathEffect(10f)
        }
    }

    override fun updateDiskCacheKey(p0: MessageDigest) {

    }

    override fun transform(
            pool: BitmapPool,
            source: Bitmap,
            outWidth: Int,
            outHeight: Int
    ): Bitmap {
        var result: Bitmap? = pool[width.toInt(), width.toInt(), Bitmap.Config.ARGB_8888]
        if (result == null) {
            result = Bitmap.createBitmap(width.toInt(), width.toInt(), Bitmap.Config.ARGB_8888)
        }
        mCanvas = Canvas(result!!)
        var circlePointX = width / 2
        var radian60 = 60 * Math.PI / 180
        var xLength = circlePointX * kotlin.math.sin(radian60)
        var yLength = circlePointX * kotlin.math.cos(radian60)
        path.reset()
        path.moveTo(circlePointX.toFloat(), 0f)
        path.lineTo(circlePointX.toFloat() + xLength.toFloat(), yLength.toFloat())
        path.lineTo(circlePointX.toFloat() + xLength.toFloat(), circlePointX + yLength.toFloat())
        path.lineTo(circlePointX.toFloat(), circlePointX.toFloat() * 2)
        path.lineTo(circlePointX.toFloat() - xLength.toFloat(), circlePointX + yLength.toFloat())
        path.lineTo(circlePointX.toFloat() - xLength.toFloat(), yLength.toFloat())
        path.close()

        mPaint.shader = BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
        mPaint.isAntiAlias = true
        mCanvas!!.drawPath(path, mPaint)
        return result!! //切记这里不能返回那个source的bitmap 要返回我们创建的只有宽高信息的bitmap
    }
}

使用自定义的transform的方法:

Glide.with(this).load(url)
   //  .apply(RequestOptions.bitmapTransform(PentagonaltTransform()))
       .transform(PentagonaltTransform(这里写ImageView的宽高))
       .listener(object : RequestListener {
             override fun onLoadFailed(p0: GlideException?, p1: Any?, p2: Target?, p3: Boolean): Boolean {
                       //当遇到网络图片加载错的时候 去加载默认的图片
                       setDefaultDrawable()
                       return false
             }

             override fun onResourceReady(p0: Drawable?, p1: Any?, p2: Target?, p3: DataSource?, p4: Boolean): Boolean {
                        return false
              }
         }).into(this)

至此自定义加载网络图片的六边形TransForm完成。

全部代码已经上传至Github:https://github.com/1169927533/BaseMavenProject/blob/master/module_customview/src/main/java/com/pince/module_customview/sixshape/PentagonalView.kt

使用方法:

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }
dependencies {
            implementation 'com.github.1169927533.BaseMavenProject:module_customview:1.4.1'
    }

你可能感兴趣的:(自定义view展示六边形图片)