Android使用setXfermode例子

Kotlin 复制代码
package com.cc.rxandroid

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View


class MyView(c: Context, a: AttributeSet): View(c, a) {

    val paint = Paint()

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        setLayerType(LAYER_TYPE_SOFTWARE, null)

        paint.color = -0x33bc
        canvas.drawBitmap(makeDst(width, height), 0f, 0f, paint)

        paint.color = -0x995501
        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        canvas.drawBitmap(makeSrc(width, height), 0f, 0f, paint)


        paint.xfermode = null
    }

    fun makeDst(w: Int, h: Int): Bitmap {
        val bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bm)
        val p = Paint(Paint.ANTI_ALIAS_FLAG)
        p.color = -0x33bc
        canvas.drawOval(RectF(0f, 0f, w * 3f / 4, h * 3f / 4), p)
        return bm
    }

    fun makeSrc(w: Int, h: Int): Bitmap {
        val bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        val canvas = Canvas(bm)
        val p = Paint(Paint.ANTI_ALIAS_FLAG)
        p.color = -0x995501
        canvas.drawRect(
            (w / 3).toFloat(), (h / 3).toFloat(), (w * 19 / 20).toFloat(),
            (h * 19 / 20).toFloat(), p
        )
        return bm
    }
}

运行效果:

不使用xfermode

使用xfermode.scr_in后

官方效果示例:

有几个使用的点要注意下:

1.绘制的源图和新图必须是bitmap,才能有官方例子的效果。

2.要关闭硬件加速。

相关推荐
01100001乄夵1 小时前
Android入门教程 - 第三章:Android布局全攻略
android·经验分享·笔记·学习方法·android期末学习
恋猫de小郭1 小时前
Snapchat 开源全新跨平台框架 Valdi ,一起来搞懂它究竟有什么特别之处
android·前端·flutter
我是好小孩9 小时前
【Android】布局优化:include、merge、ViewStub以及Inflate()源码浅析
android
GISer_Jing9 小时前
2025年Flutter与React Native对比
android·flutter·react native
MasterLi802310 小时前
我的读书清单
android·linux·学习
怪兽201410 小时前
fastjson在kotlin不使用kotlin-reflect库怎么使用?
android·开发语言·kotlin
彭同学学习日志10 小时前
Kotlin Fragment 按钮跳转报错解决:Unresolved reference ‘floatingActionButton‘
android·开发语言·kotlin
Gracker11 小时前
Android Perfetto 系列 9 - CPU 信息解读
android
Gracker11 小时前
Android Perfetto 系列 8:深入理解 Vsync 机制与性能分析
android
Gracker12 小时前
Android Perfetto 系列 07 - MainThread 和 RenderThread 解读
android