Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ public BaseViewManager(@Nullable ReactApplicationContext reactContext) {

view.setTag(R.id.use_hardware_layer, null);
view.setTag(R.id.filter, null);
view.setTag(R.id.backdrop_filter, null);
view.setTag(R.id.mix_blend_mode, null);
LayerEffectsHelper.apply(view, null, null);

Expand Down Expand Up @@ -268,6 +269,15 @@ public void setFilter(@NonNull T view, @Nullable ReadableArray filter) {
view.setTag(R.id.filter, filter);
}

@ReactProp(name = ViewProps.BACKDROP_FILTER, customType = "Filter")
public void setBackdropFilter(@NonNull T view, @Nullable ReadableArray backdropFilter) {
view.setTag(R.id.backdrop_filter, backdropFilter);
view.invalidate();
if (view.getParent() instanceof View) {
((View) view.getParent()).invalidate();
}
}

@ReactProp(name = ViewProps.MIX_BLEND_MODE)
public void setMixBlendMode(@NonNull T view, @Nullable String mixBlendMode) {
view.setTag(R.id.mix_blend_mode, BlendModeHelper.parseMixBlendMode(mixBlendMode));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ public abstract class BaseViewManagerDelegate<

ViewProps.FILTER -> mViewManager.setFilter(view, value as ReadableArray?)

ViewProps.BACKDROP_FILTER -> mViewManager.setBackdropFilter(view, value as ReadableArray?)

ViewProps.MIX_BLEND_MODE -> mViewManager.setMixBlendMode(view, value as String?)

ViewProps.SHADOW_COLOR ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,15 +117,18 @@ internal object FilterHelper {

// https://www.w3.org/TR/filter-effects-1/#blurEquivalent
fun createBlurEffect(sigma: Float, chainedEffects: RenderEffect? = null): RenderEffect? {
if (sigma <= 0.5) {
// RenderEffect.createBlurEffect takes sigma (standard deviation) directly — it passes
// through to Skia's SkImageFilters::Blur(sigmaX, sigmaY). Convert dp→px here; do NOT
// apply sigmaToRadius (that formula is for HWUI's box-filter BlurMaskFilter, not RenderEffect).
val pxSigma = PixelUtil.toPixelFromDIP(sigma)
if (pxSigma <= 0.5f) {
return null
}

val radius: Float = sigmaToRadius(sigma)
return if (chainedEffects == null) {
RenderEffect.createBlurEffect(radius, radius, Shader.TileMode.DECAL)
RenderEffect.createBlurEffect(pxSigma, pxSigma, Shader.TileMode.DECAL)
} else {
RenderEffect.createBlurEffect(radius, radius, chainedEffects, Shader.TileMode.DECAL)
RenderEffect.createBlurEffect(pxSigma, pxSigma, chainedEffects, Shader.TileMode.DECAL)
}
}

Expand Down Expand Up @@ -199,7 +202,7 @@ internal object FilterHelper {
val color: Int = if (filterValues.hasKey("color")) filterValues.getInt("color") else Color.BLACK
val radius: Float =
if (filterValues.hasKey("standardDeviation"))
sigmaToRadius(filterValues.getDouble("standardDeviation").toFloat())
PixelUtil.toPixelFromDIP(filterValues.getDouble("standardDeviation").toFloat())
else 0f

return createDropShadowEffect(offsetX, offsetY, radius, color, chainedEffects)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ public object ViewProps {
public const val BORDER_START_COLOR: String = "borderStartColor"
public const val BORDER_END_COLOR: String = "borderEndColor"
public const val BOX_SHADOW: String = "boxShadow"
public const val BACKDROP_FILTER: String = "backdropFilter"
public const val FILTER: String = "filter"
public const val MIX_BLEND_MODE: String = "mixBlendMode"
public const val OUTLINE_COLOR: String = "outlineColor"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

package com.facebook.react.views.view

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RenderEffect
import android.graphics.RenderNode
import android.os.Build
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.uimanager.FilterHelper

/**
* Helper object for applying CSS backdrop-filter effects on Android.
*
* Applies filter effects to the composited backdrop (the pixels behind a view) captured as a
* [Bitmap] snapshot. Color-matrix filters (brightness, contrast, grayscale, hue-rotate, invert,
* opacity, saturate, sepia) work on all supported API levels. Blur and drop-shadow require API 31+
* via [RenderEffect] drawn into the hardware-accelerated canvas via [RenderNode].
*/
@SuppressLint("UseRequiresApi")
internal object BackdropFilterHelper {

/**
* Draws a filtered region of [source] directly onto [canvas] at the child's position.
*
* @param canvas Hardware-accelerated canvas of the parent [ReactViewGroup].
* @param source Full-size backdrop snapshot bitmap (same dimensions as the parent view).
* @param destLeft Left coordinate of the child in parent space (canvas destination).
* @param destTop Top coordinate of the child in parent space (canvas destination).
* @param srcLeft Clamped left bound of the crop region within [source].
* @param srcTop Clamped top bound of the crop region within [source].
* @param srcRight Clamped right bound of the crop region within [source].
* @param srcBottom Clamped bottom bound of the crop region within [source].
* @param filters ReadableArray of filter descriptors as produced by processFilter.js.
*/
fun drawFilteredBackdrop(
canvas: Canvas,
source: Bitmap,
destLeft: Int,
destTop: Int,
srcLeft: Int,
srcTop: Int,
srcRight: Int,
srcBottom: Int,
filters: ReadableArray,
) {
val cropWidth = srcRight - srcLeft
val cropHeight = srcBottom - srcTop
if (cropWidth <= 0 || cropHeight <= 0) return

val cropped = Bitmap.createBitmap(source, srcLeft, srcTop, cropWidth, cropHeight)
try {
when {
FilterHelper.isOnlyColorMatrixFilters(filters) -> {
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
paint.colorFilter = FilterHelper.parseColorMatrixFilters(filters)
canvas.drawBitmap(cropped, destLeft.toFloat(), destTop.toFloat(), paint)
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
drawWithRenderEffect(canvas, cropped, destLeft.toFloat(), destTop.toFloat(), filters)
}
else -> {
// Pre-API 31: blur and drop-shadow are not supported; draw the backdrop unfiltered so
// at least the element's transparency is composited correctly.
canvas.drawBitmap(cropped, destLeft.toFloat(), destTop.toFloat(), null)
}
}
} finally {
cropped.recycle()
}
}

@TargetApi(Build.VERSION_CODES.S)
private fun drawWithRenderEffect(
canvas: Canvas,
source: Bitmap,
destLeft: Float,
destTop: Float,
filters: ReadableArray,
) {
val renderEffect: RenderEffect =
FilterHelper.parseFilters(filters)
?: run {
canvas.drawBitmap(source, destLeft, destTop, null)
return
}

val renderNode = RenderNode("backdropFilter")
renderNode.setPosition(0, 0, source.width, source.height)
renderNode.setRenderEffect(renderEffect)

val recordCanvas = renderNode.beginRecording()
recordCanvas.drawBitmap(source, 0f, 0f, null)
renderNode.endRecording()

canvas.save()
canvas.translate(destLeft, destTop)
canvas.drawRenderNode(renderNode)
canvas.restore()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

package com.facebook.react.views.view

import android.annotation.SuppressLint
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Outline
import android.graphics.RenderEffect
import android.graphics.RenderNode
import android.os.Build
import android.view.View
import com.facebook.common.logging.FLog
import com.facebook.react.R
import com.facebook.react.bridge.ReadableArray
import com.facebook.react.uimanager.FilterHelper
import java.lang.reflect.Method

/**
* Draws `backdropFilter` with the platform backdrop API (SDK 37.2+).
*
* [RenderNode.setBackdropRenderEffect] applies a [RenderEffect] to everything already drawn behind
* the node, on the RenderThread. There is no bitmap snapshot, and the backdrop includes everything
* behind the view: content of other parents, scrolling content, ancestors.
*
* The effect lives on a separate, empty [RenderNode] clipped to the view's outline (its border
* radius). Setting it on the view itself would need `clipToOutline` on the view, which would also
* clip the view's content even with `overflow: visible`.
*
* A [ReactViewGroup] draws the node at the start of its own [View.draw] ([drawBehindSelf]), so the
* node is part of the view's display list and follows its transform, opacity and visibility,
* including native-driver animations that never re-record the parent. Other views are handled by
* their parent ([drawBehindChild]).
*
* The method is looked up by reflection because React Native compiles against SDK 37.0, which does
* not have it. Remove the reflection once compileSdk is 37.2 or later.
*/
@SuppressLint("UseRequiresApi", "NewApi")
internal object NativeBackdropFilter {

private const val TAG = "NativeBackdropFilter"

// Build.VERSION_CODES_FULL value of SDK 37.2 (major * 100000 + minor).
private const val SDK_37_2 = 3_700_002

private val setBackdropRenderEffect: Method? by
lazy(LazyThreadSafetyMode.NONE) {
if (Build.VERSION.SDK_INT < 37 || Build.VERSION.SDK_INT_FULL < SDK_37_2) {
return@lazy null
}
try {
RenderNode::class.java.getMethod("setBackdropRenderEffect", RenderEffect::class.java)
} catch (e: NoSuchMethodException) {
FLog.w(TAG, "RenderNode.setBackdropRenderEffect is missing on SDK 37.2+", e)
null
}
}

/** Whether this device can draw backdrop filters natively. */
val isSupported: Boolean
get() = setBackdropRenderEffect != null

private class State(val node: RenderNode) {
var filters: ReadableArray? = null
var effect: RenderEffect? = null
}

private val outline = Outline()

/**
* Draws the filtered backdrop of [view] into its own [canvas], before anything of the view is
* drawn. Returns false when it could not be drawn natively.
*/
fun drawBehindSelf(canvas: Canvas, view: View, filters: ReadableArray): Boolean {
val node = prepare(canvas, view, filters) ?: return false
canvas.drawRenderNode(node)
return true
}

/**
* Draws the filtered backdrop of [child] into its parent's [canvas], right before the child is
* drawn. Returns false when it could not be drawn natively.
*/
fun drawBehindChild(canvas: Canvas, child: View, filters: ReadableArray): Boolean {
val node = prepare(canvas, child, filters) ?: return false
node.setAlpha(child.alpha)
val saveCount = canvas.save()
canvas.translate(child.left.toFloat(), child.top.toFloat())
if (!child.matrix.isIdentity) {
canvas.concat(child.matrix)
}
canvas.drawRenderNode(node)
canvas.restoreToCount(saveCount)
return true
}

/** Releases the node kept for [view] once its backdrop filter is removed. */
fun clear(view: View) {
val state = view.getTag(R.id.backdrop_filter_node) as? State ?: return
state.node.discardDisplayList()
view.setTag(R.id.backdrop_filter_node, null)
}

private fun prepare(canvas: Canvas, view: View, filters: ReadableArray): RenderNode? {
val method = setBackdropRenderEffect ?: return null
if (!canvas.isHardwareAccelerated) return null

val width = view.width
val height = view.height
if (width <= 0 || height <= 0) return null

val state =
view.getTag(R.id.backdrop_filter_node) as? State
?: State(RenderNode("backdropFilter")).also {
view.setTag(R.id.backdrop_filter_node, it)
}

if (state.filters !== filters) {
state.filters = filters
state.effect = FilterHelper.parseFilters(filters)
try {
method.invoke(state.node, state.effect)
} catch (e: Exception) {
FLog.w(TAG, "setBackdropRenderEffect failed", e)
return null
}
}
if (state.effect == null) return null

val node = state.node
node.setPosition(0, 0, width, height)
node.setOutline(outlineOf(view, width, height))
node.setClipToOutline(true)

// An empty node is not drawn; a transparent fill keeps it without adding pixels on top of the
// processed backdrop.
val recording = node.beginRecording(width, height)
recording.drawColor(Color.TRANSPARENT)
node.endRecording()
return node
}

private fun outlineOf(view: View, width: Int, height: Int): Outline {
outline.setEmpty()
// A view sets its background's bounds while drawing the background, which happens after this
// node is drawn. Without bounds the background's rounded outline is empty and clips everything.
view.background?.let { background ->
val bounds = background.bounds
if (bounds.width() != width || bounds.height() != height) {
background.setBounds(0, 0, width, height)
}
}
view.outlineProvider?.getOutline(view, outline)
if (outline.isEmpty) {
outline.setRect(0, 0, width, height)
}
return outline
}
}
Loading