1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package cn.flightfeather.thirdappmodule.util.photo
 
import android.app.Activity
import android.content.res.Resources
import android.graphics.*
import android.os.Build
import android.support.annotation.ColorInt
import android.util.DisplayMetrics
import android.widget.TextView
import cn.flightfeather.thirdappmodule.R
import cn.flightfeather.thirdappmodule.util.DateFormatter
import cn.flightfeather.thirdappmodule.util.dp
import cn.flightfeather.thirdappmodule.util.sp
import org.jetbrains.anko.backgroundColor
import java.util.*
import java.util.regex.Pattern
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
 
/**
 * @author riku
 * Date: 2020/5/9
 * 图片、文本合并工具
 * 规定合并的图片为1~3张, 其中纵向的图片规定宽度保持为屏幕宽度的1/3进行缩放, 横向的图则根据图片张数和横纵组合自适应,具体看代码.
 */
class ImageMergeUtil(activity: Activity) {
 
    private val padding = 4F.dp
    private val bgWidth:Float
    private val bgHeight: Float
    private val textPaint:Paint
    private val textPaint2:Paint
    private val indexPaint:Paint
    private val titlePaint:Paint
 
    //设定每行最大图片数
    val colNum = 3
 
    init {
        val dm = DisplayMetrics()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            activity.windowManager.defaultDisplay.getRealMetrics(dm)
        } else {
            activity.windowManager.defaultDisplay.getMetrics(dm)
        }
        bgWidth = dm.widthPixels.toFloat()
        bgHeight = dm.heightPixels.toFloat()
 
        textPaint = Paint().apply {
            textAlign = Paint.Align.LEFT
            color = Color.BLACK
            style = Paint.Style.FILL
//            strokeWidth = density * 2
            isAntiAlias = true
            textSize = 14f.sp
        }
        textPaint2 = Paint().apply {
            textAlign = Paint.Align.LEFT
            color = Color.WHITE
            style = Paint.Style.FILL_AND_STROKE
//            strokeWidth = density * 2
            isAntiAlias = true
            textSize = 14f.sp
        }
        indexPaint = Paint().apply {
            textAlign = Paint.Align.CENTER
            color = Color.BLACK
            style = Paint.Style.FILL
//            strokeWidth = density * 2
            isAntiAlias = true
            textSize = 14f.sp
        }
        titlePaint = Paint().apply {
            textAlign = Paint.Align.LEFT
            color = Color.BLACK
            style = Paint.Style.FILL
            isAntiAlias = true
            textSize = 14f.sp
            typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
        }
    }
 
    /**
     * 给图片添加水印
     * 默认水印
     */
    fun addLogo(bitmap: Bitmap, logo: Bitmap): Bitmap {
        // 默认水印宽度为图片的 1/8
        val newLogo = resizeBitmap(logo, bitmap.width.toFloat() / 7)
        val newBitmap = Bitmap.createBitmap(bitmap.width, bitmap.height, bitmap.config)
        val canvas = Canvas(newBitmap)
        canvas.drawBitmap(bitmap, 0f, 0f, null)
        val margin = 24f// 设定logo和图片的边距
        val x = bitmap.width - newLogo.width - margin
        val y = margin
        canvas.drawBitmap(newLogo, x, y, null)
 
        return newBitmap
    }
 
    fun mergeImage(bitmaps: MutableList<Bitmap>): Bitmap? {
        var result: Bitmap? = null
        val lengthWays = isLengthWays(bitmaps)
 
        when (bitmaps.size) {
            1 -> {
                when (lengthWays) {
                    "h" -> {
                        val b = resizeBitmap(bitmaps[0], (bgWidth - padding * 4) / 3)
                        result = createCanvas(b.width + padding.toInt() * 2, b.height + padding.toInt() * 2) {
                            it.drawBitmap(b, padding, padding, null)
                        }
                    }
                    "w" -> {
                        val b = resizeBitmap(bitmaps[0], newHeight = (bgHeight - padding * 2) / 4)
                        result = createCanvas(b.width + padding.toInt() * 2, b.height + padding.toInt() * 2) {
                            it.drawBitmap(b, padding, padding, null)
                        }
                    }
                }
            }
            2 -> {
                when (lengthWays) {
                    "hh" -> {
                        val b0 = resizeBitmap(bitmaps[0], (bgWidth - padding * 4) / 3)
                        val b1 = resizeBitmap(bitmaps[1], (bgWidth - padding * 4) / 3)
                        result = createCanvas(b0.width + b1.width + padding.toInt() * 3, b0.height + padding.toInt() * 2) {
                            it.drawBitmap(b0, padding, padding, null)
                            it.drawBitmap(b1, b0.width + padding * 2, padding, null)
                        }
                    }
                    "hw" -> {
                        val b0 = resizeBitmap(bitmaps[0], (bgWidth - padding * 4) / 3)
                        val b1 = resizeBitmap(bitmaps[1], newHeight = b0.height.toFloat())
                        result = createCanvas(b0.width + b1.width + padding.toInt() * 3, b0.height + padding.toInt() * 2) {
                            it.drawBitmap(b0, padding, padding, null)
                            it.drawBitmap(b1, b0.width + padding * 2, padding, null)
                        }
                    }
                    "ww" -> {
                        val b0 = bitmaps[1]
                        var b1 = bitmaps[1]
                        if (bitmaps[0].height != bitmaps[1].width) {
                            b1 = resizeBitmap(bitmaps[1], newHeight = bitmaps[0].height.toFloat())
                        }
                        result = createCanvas(b0.width + b1.width + padding.toInt() * 3, b0.height + padding.toInt() * 2) {
                            it.drawBitmap(b0, padding, padding, null)
                            it.drawBitmap(b1, b0.width + padding * 2, padding, null)
                        }
                    }
                }
            }
            3 -> {
                when (lengthWays) {
                    "hhh" -> {
                        val b0 = resizeBitmap(bitmaps[0], (bgWidth - padding * 4) / 3)
                        val b1 = resizeBitmap(bitmaps[1], (bgWidth - padding * 4) / 3)
                        val b2 = resizeBitmap(bitmaps[2], (bgWidth - padding * 4) / 3)
                        result = createCanvas((b0.width + padding.toInt()) * 3, b0.height + padding.toInt() * 2) {
                            it.drawBitmap(b0, padding, padding, null)
                            it.drawBitmap(b1, b0.width + padding * 2, padding, null)
                            it.drawBitmap(b2, b0.width + b1.width + padding * 3, padding, null)
                        }
                    }
                    "hww" -> {
                        val b0 = resizeBitmap(bitmaps[0], (bgWidth - padding * 4) / 3)
                        val b1 = resizeBitmap(bitmaps[1], newHeight = (b0.height - padding) / 2)
                        val b2 = resizeBitmap(bitmaps[2], newHeight = (b0.height - padding) / 2)
                        result = createCanvas(b0.width + b1.width + padding.toInt() * 3, b0.height + padding.toInt() * 2) {
                            it.drawBitmap(b0, padding, padding, null)
                            it.drawBitmap(b1, b0.width + padding * 2, padding, null)
                            it.drawBitmap(b2, b0.width + padding * 2, b1.height + padding, null)
                        }
                    }
                    "hhw" -> {
                        val b0 = resizeBitmap(bitmaps[0], (bgWidth - padding * 4) / 3)
                        val b1 = resizeBitmap(bitmaps[1], (bgWidth - padding * 4) / 3)
                        val b2 = resizeBitmap(bitmaps[2], b0.width.toFloat() * 2 + padding)
                        result = createCanvas((b0.width + padding.toInt()) * 3, b0.height + padding.toInt() * 2) {
                            it.drawBitmap(b0, padding, padding, null)
                            it.drawBitmap(b1, b0.width + padding * 2, padding, null)
                            it.drawBitmap(b2, padding, b0.height + padding, null)
                        }
                    }
                    "www" -> {
                        val b0 = bitmaps[0]
                        var b1 = bitmaps[1]
                        var b2 = bitmaps[2]
                        if (b1.width != b0.width) {
                            b1 = resizeBitmap(b1, b0.width.toFloat())
                        }
                        if (b2.width != b0.width) {
                            b2 = resizeBitmap(b2, b0.width.toFloat())
                        }
                        result = createCanvas(b0.width + padding.toInt() * 2, b0.height + padding.toInt() * 2) {
                            it.drawBitmap(b0, padding, padding, null)
                            it.drawBitmap(b1, padding, b0.height + padding * 2, null)
                            it.drawBitmap(b2, padding, b0.height * 2 + padding * 3, null)
                        }
                    }
                }
            }
 
        }
 
        return result
    }
 
    /**
     * 返回图片的横向, 纵向组合信息
     * 确保纵向图片永远排在前面
     * @param bitmaps 图片数量
     * @return w: 横向; h: 纵向
     */
    private fun isLengthWays(bitmaps: MutableList<Bitmap>): String {
        var result = ""
        val tempList = mutableListOf<Bitmap>()
 
        bitmaps.forEach {
            if (it.width >= it.height) {
                tempList.add(it)
                result += "w"
            } else {
                tempList.add(0,it)
                result = "h$result"
            }
        }
        bitmaps.clear()
        bitmaps.addAll(tempList)
        return result
    }
 
    fun mergeVertical(bitmap1: Bitmap, bitmap2: Bitmap): Bitmap {
        val result: Bitmap
        val width = max(bitmap1.width, bitmap2.width)
        if (bitmap2.width != bitmap1.width && (bitmap1.width > bgWidth || bitmap2.width > bgWidth)) {
            val h2 = bitmap2.height * width / bitmap2.width
            result = Bitmap.createBitmap(width, bitmap1.height + h2, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(result)
            val newBitmap2 = resizeBitmap(bitmap2, width.toFloat(), h2.toFloat())
            canvas.drawBitmap(bitmap1, 0F, padding * 4, null)
            canvas.drawBitmap(newBitmap2, 0F, bitmap1.height.toFloat() + padding, null)
        } else {
            result = Bitmap.createBitmap(width, bitmap1.height + bitmap2.height, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(result)
            canvas.drawBitmap(bitmap1, 0F, padding, null)
            canvas.drawBitmap(bitmap2, 0F, bitmap1.height.toFloat() + padding * 4, null)
        }
        return result
    }
 
    fun mergeHorizontal(bitmap1: Bitmap, bitmap2: Bitmap): Bitmap {
        val result: Bitmap
        val height = bitmap1.height
        if (bitmap2.height != height) {
            val w2 = bitmap2.width * height / bitmap2.height
            result = Bitmap.createBitmap(
                    (bitmap1.width + w2 + padding * 3).toInt(),
                    (height + padding * 2).toInt(),
                    Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(result)
            val newBitmap2 = resizeBitmap(bitmap2, w2.toFloat(), height.toFloat())
            canvas.drawBitmap(bitmap1, padding, padding, null)
            canvas.drawBitmap(newBitmap2, bitmap1.width.toFloat() + padding * 2, padding, null)
        } else {
            result = Bitmap.createBitmap(
                    (bitmap1.width + bitmap2.width + padding * 3).toInt(),
                    (height + padding * 2).toInt(), Bitmap.Config.ARGB_8888
            )
            val canvas = Canvas(result)
            canvas.drawBitmap(bitmap1, padding, padding, null)
            canvas.drawBitmap(bitmap2, bitmap1.width.toFloat() + padding * 2, padding, null)
        }
        return result
    }
 
    /**
     * 合并图片和一段文字
     * 当图片的宽度大于屏幕宽度时,默认将文本合成在图片下方
     * 当图片的宽度小于屏幕宽度时,默认将文本合成在图片右侧
     */
    fun mergeVerticalText(bitmap: Bitmap, text: String, title: String? = null, titleIcon: Int = 0, res: Resources? = null): Bitmap {
 
        var textMaxWidth = bgWidth - padding * 2
 
        if (bitmap.width < bgWidth / 2) {
            textMaxWidth = bgWidth - bitmap.width - padding * 2
        }
 
        val bounds = Rect()
        var textArray = arrayOf<String>()
 
        /* 中文字符,首行缩进 */
        val p = Pattern.compile("[\u4e00-\u9fa5]")
        val m = p.matcher(text)
        val textIndent = if (m.find()) {
            "\u3000\u3000$text"
//            text
        } else {
            text
        }
 
        /* 文本换行 */
        textArray = linefeed(textIndent, textMaxWidth, textPaint)
 
        val fontMetrics = textPaint.fontMetrics
        val textHeight = fontMetrics.bottom - fontMetrics.top
        val totalTextHeight = textHeight * textArray.size
 
        /* 根据屏幕大小重绘新的图片宽高,确保文本字体显示不会被缩小 */
        val scaledBitmap = if (bitmap.width > bgWidth) {
            resizeBitmap(bitmap, bgWidth, bitmap.height * bgWidth / bitmap.width)
        } else {
            bitmap
        }
        val newWidth = max(scaledBitmap.width, bgWidth.toInt())
        var newHeight = scaledBitmap.height + padding.toInt() * 5 + totalTextHeight.toInt()
        if (scaledBitmap.width < bgWidth / 2) {
            newHeight = max(scaledBitmap.height, totalTextHeight.toInt()) + padding.toInt() * 2
        } else if (title != null) {
            val fm = titlePaint.fontMetrics
            val h = fm.bottom - fm.top
            newHeight += (h + padding).toInt()
        }
        val newBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(newBitmap)
        canvas.drawBitmap(scaledBitmap, 0F, 0F, null)
 
        var x = padding
        var y = scaledBitmap.height + padding - fontMetrics.top
        if (scaledBitmap.width < bgWidth / 2) {
            x = scaledBitmap.width.toFloat()
            y = -fontMetrics.top
        }
        if (title != null) {
            val fm = titlePaint.fontMetrics
            val h = fm.bottom - fm.top
            val options = BitmapFactory.Options().apply {
                outWidth = h.toInt()
                outHeight = h.toInt()
            }
            val icon = BitmapFactory.decodeResource(res, titleIcon, options)
            canvas.drawBitmap(icon, x, y + fm.ascent, null)
            canvas.drawText(title, x + h + padding, y, titlePaint)
            y += h + padding
        }
        textArray.forEach {
            canvas.drawText(it, x, y, textPaint)
            y += textHeight
        }
 
        return newBitmap
    }
 
    fun mergeText(bitmap1: Bitmap, textView: TextView, coordinateO: Pair<Float, Float>, xScale: Float, yScale: Float): Bitmap {
        textPaint2.textSize = textView.textSize
        var coordinate = coordinateO
        var textMaxWidth = bgWidth - coordinate.first * 2
        /* 根据屏幕大小重绘新的图片宽高,确保文本字体显示不会被缩小 */
        val scaledBitmap = if (bitmap1.width > bgWidth) {
            val y = coordinate.second / bgHeight * bitmap1.height
            coordinate = Pair(coordinate.first, y)
            textPaint2.textSize = textPaint2.textSize / bgHeight * bitmap1.height
            textMaxWidth = bitmap1.width - coordinate.first * 2
//            resizeBitmap(bitmap1, bgWidth)
            Bitmap.createBitmap(bitmap1.width, bitmap1.height, bitmap1.config)
        } else {
            Bitmap.createBitmap(bitmap1.width, bitmap1.height, bitmap1.config)
        }
 
        val fontMetrics = textPaint2.fontMetrics
        val textHeight = abs(fontMetrics.bottom) + abs(fontMetrics.ascent)
        /* 文本换行 */
        val textArray = linefeed(textView.text.toString(), textMaxWidth, textPaint2)
        val canvas = Canvas(scaledBitmap)
        canvas.drawBitmap(bitmap1, 0F, 0F, null)
 
        var y = scaledBitmap.height * yScale + abs(fontMetrics.top)
        val x = scaledBitmap.width * xScale
        textArray.forEach {
            textPaint2.color = Color.BLACK
            canvas.drawText(it, x + 3, y + 3, textPaint2)
            textPaint2.color = Color.WHITE
            canvas.drawText(it, x, y, textPaint2)
            y += textHeight
        }
        return scaledBitmap
    }
 
    fun createTitle(text: String, time: Date?): Bitmap {
        val timeStr = DateFormatter.dateFormat.format(time)
        val tFm = textPaint.fontMetrics
        val tH = tFm.bottom - tFm.top
 
        val b = Bitmap.createBitmap(bgWidth.toInt(), 1, Bitmap.Config.ARGB_8888)
 
        val textMaxWidth = bgWidth - padding * 2
        val textArray = linefeed(text, textMaxWidth, titlePaint)
        val fm = titlePaint.fontMetrics
        val h = fm.bottom - fm.top
 
 
        val result = Bitmap.createBitmap(bgWidth.toInt(), (b.height + h * textArray.size + tH + padding * 2).roundToInt(), Bitmap.Config.ARGB_8888)
        var y = padding + b.height - fm.top
        Canvas(result).apply {
            textArray.forEach {
                val x = max(bgWidth / 2 - titlePaint.measureText(it) / 2, padding)
                drawText(it, x, y, titlePaint)
                y += h
            }
            y -= h
            val tWidth = textPaint.measureText(timeStr)
            val x = bgWidth - padding - tWidth
            y += tH
            drawText(timeStr, x, y, textPaint)
        }
        return result
    }
 
    fun mergeIndex(bitmap: Bitmap, index: Int, res: Resources): Bitmap {
        val l = "-"
        val indexText = if (index < 10) {
            "0$index"
        } else {
            "$index"
        }
 
        val indexWidth = indexPaint.measureText(indexText)
        val halfWidth = (bitmap.width - indexWidth - padding * 4) / 2
        val w = textPaint.measureText(l)
        val count = (halfWidth / w).toInt()
        val label = StringBuilder()
        repeat(count) {
            label.append(l)
        }
        val labelWidth = textPaint.measureText(label.toString())
 
        val indexFm = indexPaint.fontMetrics
        val labelFm = textPaint.fontMetrics
 
        val imageWidth = max(indexWidth, indexFm.bottom - indexFm.top)
        val options = BitmapFactory.Options().apply {
            outWidth = imageWidth.toInt()
            outHeight = imageWidth.toInt()
        }
        val image = BitmapFactory.decodeResource(res, R.mipmap.ic_feiyu, options)
        val h = max((indexFm.bottom - indexFm.top) * 2, labelFm.bottom - labelFm.top) + padding
 
        val result = Bitmap.createBitmap(bitmap.width, bitmap.height + h.toInt(), Bitmap.Config.ARGB_8888)
        val canvas = Canvas(result)
        canvas.drawBitmap(bitmap, 0F, 0F, null)
        canvas.drawText(label.toString(), 0F, bitmap.height + padding * 2 - indexFm.top + indexFm.bottom, textPaint)
        canvas.drawText(label.toString(), bitmap.width - labelWidth, bitmap.height + padding * 2 - indexFm.top + indexFm.bottom, textPaint)
        val centreX = bitmap.width / 2
        canvas.drawText(indexText, centreX - indexWidth / 2, bitmap.height + padding * 2 - indexFm.top, textPaint)
        canvas.drawBitmap(image, centreX - imageWidth / 2, bitmap.height + padding * 2 - indexFm.top + indexFm.bottom, null)
 
        return result
    }
 
    fun mergeTitle(bitmap: Bitmap, title: String): Bitmap {
        titlePaint
        return bitmap
    }
 
    fun drawBg(bitmap: Bitmap, @ColorInt bgColor: Int): Bitmap {
        Canvas(bitmap).drawColor(bgColor, PorterDuff.Mode.DST_OVER)
        return bitmap
    }
 
    private fun createCanvas(width: Int, height: Int, onDraw: (canvas: Canvas) -> Unit): Bitmap {
        val b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        onDraw(Canvas(b))
        return b
    }
 
    private fun resizeBitmap(bitmap: Bitmap, newWidth: Float? = null, newHeight: Float? = null): Bitmap {
        var scaleW = newWidth?.let { it / bitmap.width }
        var scaleH = newHeight?.let { it / bitmap.height }
        if (scaleW == null && scaleH == null) {
            scaleW = 1F
            scaleH = 1F
        }else if (scaleW == null) {
            scaleW = scaleH
        } else {
            scaleH = scaleW
        }
        val matrix = Matrix()
        matrix.postScale(scaleW!!, scaleH!!)
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
    }
 
    /**
     * 文本换行
     */
    private fun linefeed(textIndent: String, textMaxWidth: Float, paint: Paint): Array<String> {
        var textArray = arrayOf<String>()
        val str = StringBuilder()
        for (i in textIndent.indices) {
            str.append(textIndent[i])
            //measureText 在计算文本宽度时,会包含空格
            val width = paint.measureText(str.toString())
            //getTextBounds 在计算宽度时,会忽略掉空格
//            textPaint.getTextBounds(str.toString(), 0, str.length, bounds)
 
            if (width > textMaxWidth) {
                val lastChar = str.last()
                val chars = str.deleteCharAt(str.lastIndex)
                textArray = textArray.plus(chars.toString())
                str.clear()
                str.append(lastChar)
            }
        }
        if (str.isNotEmpty()) {
            textArray = textArray.plus(str.toString())
        }
        return textArray
    }
 
}