簡體   English   中英

在 Android 中以編程方式使用漸變的色調圖標

[英]Tint icon with gradient programatically in Android

我有一個必須以編程方式着色的圖標。 我從后端收到兩個 colors 作為字符串(例如“#FFFFFF”和“#AAAAAA”),其中一個將用作 startGradient 值,另一個用作 endGradient 值。

下一行以編程方式創建漸變

val startGradientColor = Color.parseColor(it.gradientStart)
val endGradientColor = Color.parseColor(it.gradientEnd)
val grad = GradientDrawable(TOP_BOTTOM, intArrayOf(startGradientColor, endGradientColor))
grad.cornerRadius = 0f

創建漸變后,我只需要為圖標着色。 我嘗試將漸變設置為背景,但是這種方法 colors 是背景而不是圖標。 下面是我試過的代碼。

binding.leagueBadge.background = grad

我希望你們有解決方案。 提前致謝

好吧,伙計們,我找到了一個棘手的解決方案。 但是,我希望 Android 盡快實現一個干凈直接的方法來做到這一點。

讓我們看看解決方案:

對於以編程方式為圖像設置漸變的情況,我將圖像重繪為 imageview。 下面的方法將 imageview 轉換為 bitmap,手動設置高度和寬度(這些值必須保持原始資產的縱橫比,以免修改原始資產)並傳遞漸變 Z62848E3CE5804AA982513A7922FF8.7 Colors 是我創建的 object 包含字符串(gradientStart 和 gradientEnd)

fun setImageWithGradient(imageview: ImageView, width : Int, height : Int, colors: Colors) {
        val myBitmap = (imageview.drawable).toBitmap(width, height)
        val newBitmap = addGradient(myBitmap, colors)
        imageview.setImageDrawable(BitmapDrawable(resources, newBitmap))
    }

The method above redraws the bitmap received, applies the gradient (colors object I mentioned above) and return the bitmap (asset with the gradient applied) Then you may set this bitmap returned into the imageview desired.

fun addGradient(originalBitmap: Bitmap, colors: Colors): Bitmap? {
        val width = originalBitmap.width
        val height = originalBitmap.height
        val updatedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(updatedBitmap)
        canvas.drawBitmap(originalBitmap, 0.toFloat(), 0.toFloat(), null)
        val paint = Paint()
        val shader = LinearGradient(0.toFloat(), 0.toFloat(), 0.toFloat(), height.toFloat(), Color.parseColor(colors.gradientStart), Color.parseColor(colors.gradientEnd), Shader.TileMode.CLAMP)
        paint.shader = shader
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawRect(0.toFloat(), 0.toFloat(), width.toFloat(), height.toFloat(), paint)
        return updatedBitmap
    }

對於將漸變應用到 CardView 背景的情況,我沒有找到不同的方法,而是在 CardView 內添加了一個相對布局,大小與父級匹配。 然后,不將漸變應用到 CardView 的背景,而是應用到 RelativeLayout 的背景。

下面的方法就是這樣做的:

private fun setMedalRankingColor(gradientColors: Colors) {
        val color = intArrayOf(Color.parseColor(gradientColors.gradientStart), Color.parseColor(gradientColors.gradientEnd))
        val gradient = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, color)
        gradient.cornerRadius = 0f
        binding.medal.background = gradient
    }

我希望對某人有所幫助,如果比這更好,請隨時分享您的解決方案。

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM