Skip to content

Commit 0ea7132

Browse files
feat(android) - url function support in backgroundImage
## Summary: - Adds support for loading images with `url` syntax. e.g. `backgroundImage: url("https://example.com/1.png")`. - `background-repeat: round` now uses at least one tile, as CSS requires. This also changes gradients whose tile is more than twice the size of the box. - This PR only includes android code changes. To fully test the PR, merge #58246 (JS/parser) and #58248 (iOS) into this one. > Recreated from #54994, which was auto-closed when my fork was deleted. GitHub does not allow reopening a PR whose head repository is gone. Rebased onto current `main`. ### How: Uses Fresco's image pipeline to fetch the image in `BackgroundImageURLLoader`. Keeps Fresco's `CloseableReference` open and draws the shared bitmap in the `BackgroundImageDrawable` canvas using `drawBitmap`, like Fresco's drawee. Background images with the same url share one bitmap. The reference is released when the url changes or the view is dropped. ## Changelog: [ANDROID] [ADDED] - `url` support with `backgroundImage` ## Test Plan: - Merge #58246, this PR and #58248, then test the examples added in the JS PR. - Added unit tests: `./gradlew :packages:react-native:ReactAndroid:testDebugUnitTest --tests 'com.facebook.react.uimanager.drawable.*' --tests 'com.facebook.react.uimanager.style.BackgroundImageLayerTest'` ### Screenshots Each `url()` example in RN Tester, opened by deep link, on the Android emulator, with all three PRs merged: | URL Image | URL Image from local file | Local file at its natural size (@3x asset, 33x33) | | --- | --- | --- | | <img src="https://raw.githubusercontent.com/intergalacticspacehighway/react-native/c7893b2cc494b383efc609a82f71b1ceda0e6411/android-1.png" width="100" /> | <img src="https://raw.githubusercontent.com/intergalacticspacehighway/react-native/c7893b2cc494b383efc609a82f71b1ceda0e6411/android-2.png" width="100" /> | <img src="https://raw.githubusercontent.com/intergalacticspacehighway/react-native/c7893b2cc494b383efc609a82f71b1ceda0e6411/android-3.png" width="100" /> | ### Follow-ups - Decode images at the size they are drawn, instead of full size. - `cover` and `contain` support for `backgroundSize`. Differential Revision: D131256210 Pull Request resolved: #58247
1 parent 3c504a7 commit 0ea7132

7 files changed

Lines changed: 508 additions & 39 deletions

File tree

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/BackgroundStyleApplicator.kt‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ public object BackgroundStyleApplicator {
9393
ensureBackgroundImageDrawable(view).backgroundImageLayers = backgroundImageLayers
9494
}
9595

96+
@JvmStatic
97+
internal fun cancelBackgroundImageURLRequests(view: View) {
98+
getBackgroundImage(view)?.cancelBackgroundImageURLRequests()
99+
}
100+
96101
@JvmStatic
97102
internal fun setBackgroundSize(view: View, backgroundSizes: List<BackgroundSize>?) {
98103
ensureBackgroundImageDrawable(view).backgroundSize = backgroundSizes

‎packages/react-native/ReactAndroid/src/main/java/com/facebook/react/uimanager/drawable/BackgroundImageDrawable.kt‎

Lines changed: 97 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@ import android.graphics.PixelFormat
1616
import android.graphics.Rect
1717
import android.graphics.RectF
1818
import android.graphics.drawable.Drawable
19+
import com.facebook.common.logging.FLog
20+
import com.facebook.react.common.ReactConstants
1921
import com.facebook.react.uimanager.FloatUtil
2022
import com.facebook.react.uimanager.LengthPercentage
2123
import com.facebook.react.uimanager.LengthPercentageType
@@ -46,39 +48,62 @@ internal fun calculateBackgroundImageSize(
4648
imageHeight: Float,
4749
backgroundSize: BackgroundSize?,
4850
repeat: BackgroundRepeat?,
51+
hasIntrinsicRatio: Boolean = false,
4952
): Pair<Float, Float> {
5053
var finalWidth = imageWidth
5154
var finalHeight = imageHeight
55+
// An `auto` dimension keeps the image's aspect ratio. Without a ratio (gradients), it stays at
56+
// its intrinsic size.
57+
val keepsRatio = hasIntrinsicRatio && imageWidth > 0 && imageHeight > 0
58+
val ratio = if (keepsRatio) imageWidth / imageHeight else 0f
59+
var xAuto = true
60+
var yAuto = true
5261

5362
if (backgroundSize is BackgroundSize.LengthPercentageAuto) {
5463
val w = backgroundSize.lengthPercentage.x
5564
val h = backgroundSize.lengthPercentage.y
65+
xAuto = backgroundSize.lengthPercentage.isXAuto()
66+
yAuto = backgroundSize.lengthPercentage.isYAuto()
5667
if (w != null) {
5768
finalWidth = positionToPixels(w, containerWidth)
5869
}
5970
if (h != null) {
6071
finalHeight = positionToPixels(h, containerHeight)
6172
}
73+
if (keepsRatio) {
74+
if (!xAuto && yAuto) {
75+
finalHeight = finalWidth / ratio
76+
} else if (xAuto && !yAuto) {
77+
finalWidth = finalHeight * ratio
78+
}
79+
}
6280
}
6381

6482
if (repeat?.x == BackgroundRepeatKeyword.Round && finalWidth > 0) {
6583
if (!FloatUtil.floatsEqual(containerWidth.rem(finalWidth), 0f)) {
66-
val numRepeats = round(containerWidth / finalWidth)
67-
if (numRepeats > 0) {
68-
finalWidth = containerWidth / numRepeats
69-
}
84+
// CSS rounds to the nearest whole number of tiles, but at least one.
85+
val numRepeats = maxOf(1f, round(containerWidth / finalWidth))
86+
finalWidth = containerWidth / numRepeats
7087
}
7188
}
7289

7390
if (repeat?.y == BackgroundRepeatKeyword.Round && finalHeight > 0) {
7491
if (!FloatUtil.floatsEqual(containerHeight.rem(finalHeight), 0f)) {
75-
val numRepeats = round(containerHeight / finalHeight)
76-
if (numRepeats > 0) {
77-
finalHeight = containerHeight / numRepeats
78-
}
92+
// CSS rounds to the nearest whole number of tiles, but at least one.
93+
val numRepeats = maxOf(1f, round(containerHeight / finalHeight))
94+
finalHeight = containerHeight / numRepeats
7995
}
8096
}
8197

98+
// With `round` on one axis only, an `auto` other axis is scaled again to restore the ratio.
99+
val roundX = repeat?.x == BackgroundRepeatKeyword.Round
100+
val roundY = repeat?.y == BackgroundRepeatKeyword.Round
101+
if (keepsRatio && roundX && !roundY && yAuto) {
102+
finalHeight = finalWidth / ratio
103+
} else if (keepsRatio && roundY && !roundX && xAuto) {
104+
finalWidth = finalHeight * ratio
105+
}
106+
82107
return finalWidth to finalHeight
83108
}
84109

@@ -95,11 +120,13 @@ internal class BackgroundImageDrawable(
95120
private var backgroundImageClipPath: Path? = null
96121
private var backgroundPositioningArea: RectF? = null
97122
private var backgroundPaintingArea: RectF? = null
123+
private val backgroundImageURLLoader = BackgroundImageURLLoader(context) { invalidateSelf() }
98124

99125
var backgroundImageLayers: List<BackgroundImageLayer>? = null
100126
set(value) {
101127
if (field != value) {
102128
field = value
129+
backgroundImageURLLoader.loadBackgroundImages(value.orEmpty())
103130
invalidateSelf()
104131
}
105132
}
@@ -129,7 +156,12 @@ internal class BackgroundImageDrawable(
129156
}
130157

131158
private val backgroundPaint: Paint =
132-
Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
159+
Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG).apply { style = Paint.Style.FILL }
160+
161+
/** Called when the view is dropped. */
162+
fun cancelBackgroundImageURLRequests() {
163+
backgroundImageURLLoader.cancelRequests()
164+
}
133165

134166
override fun invalidateSelf() {
135167
needUpdatePath = true
@@ -166,7 +198,7 @@ internal class BackgroundImageDrawable(
166198
}
167199

168200
override fun draw(canvas: Canvas) {
169-
if (backgroundImageLayers == null || backgroundImageLayers?.isEmpty() == true) {
201+
if (backgroundImageLayers.isNullOrEmpty()) {
170202
return
171203
}
172204

@@ -195,23 +227,53 @@ internal class BackgroundImageDrawable(
195227
val position =
196228
backgroundPosition?.takeIf { it.isNotEmpty() }?.let { it.getOrNull(index % it.size) }
197229

230+
val uri = backgroundImageLayer.uri
231+
val urlImage: BackgroundImageURLLoader.LoadedImage?
232+
val (intrinsicWidth, intrinsicHeight) =
233+
if (uri == null) {
234+
urlImage = null
235+
backgroundPositioningArea.width() to backgroundPositioningArea.height()
236+
} else {
237+
val image = backgroundImageURLLoader.imageForUri(uri)
238+
if (image == null) {
239+
continue
240+
}
241+
urlImage = image
242+
// Asset (local require() assets) pass intrinsicWidth/Height in DIPs
243+
// So use those dimensions and convert from dp to physical pixels.
244+
val assetWidth = backgroundImageLayer.intrinsicWidth
245+
val assetHeight = backgroundImageLayer.intrinsicHeight
246+
if (assetWidth != null && assetHeight != null) {
247+
assetWidth.dpToPx() to assetHeight.dpToPx()
248+
} else {
249+
// Plain url() images don't pass intrinsic width/height
250+
// so take the image's natural pixels as DIPs and convert
251+
image.width.dpToPx() to image.height.dpToPx()
252+
}
253+
}
254+
198255
// 2. Calculate the size of a single tile.
199256
val (tileWidth, tileHeight) =
200257
calculateBackgroundImageSize(
201258
backgroundPositioningArea.width(),
202259
backgroundPositioningArea.height(),
203-
backgroundPositioningArea.width(),
204-
backgroundPositioningArea.height(),
260+
intrinsicWidth,
261+
intrinsicHeight,
205262
size,
206263
repeat,
264+
hasIntrinsicRatio = uri != null,
207265
)
208266

209267
if (tileWidth <= 0 || tileHeight <= 0) {
210268
continue
211269
}
212270

213-
// 3. Set paint shader
214-
backgroundPaint.setShader(backgroundImageLayer.getShader(tileWidth, tileHeight))
271+
// 3. Set paint shader for gradients (URL images don't use shaders)
272+
if (uri == null) {
273+
backgroundPaint.setShader(backgroundImageLayer.getShader(tileWidth, tileHeight))
274+
} else {
275+
backgroundPaint.setShader(null)
276+
}
215277

216278
// 4. Calculate spacing, x and y tiles count and position for tiles
217279
var (initialX, initialY) = calculateBackgroundPosition(tileWidth, tileHeight, position)
@@ -303,18 +365,30 @@ internal class BackgroundImageDrawable(
303365
}
304366

305367
// 5. draw the repeating tiles using translate
368+
val urlImageMatrix = urlImage?.drawMatrix(tileWidth, tileHeight)
306369
var translateX = initialX
307370
var translateY: Float
308-
repeat(xTilesCount) {
309-
translateY = initialY
310-
repeat(yTilesCount) {
311-
canvas.save()
312-
canvas.translate(translateX, translateY)
313-
canvas.drawRect(0f, 0f, tileWidth, tileHeight, backgroundPaint)
314-
canvas.restore()
315-
translateY += tileHeight + ySpacing
371+
val saveCount = canvas.saveCount
372+
try {
373+
repeat(xTilesCount) {
374+
translateY = initialY
375+
repeat(yTilesCount) {
376+
canvas.save()
377+
canvas.translate(translateX, translateY)
378+
if (urlImage != null && urlImageMatrix != null) {
379+
canvas.drawBitmap(urlImage.bitmap, urlImageMatrix, backgroundPaint)
380+
} else {
381+
canvas.drawRect(0f, 0f, tileWidth, tileHeight, backgroundPaint)
382+
}
383+
canvas.restore()
384+
translateY += tileHeight + ySpacing
385+
}
386+
translateX += tileWidth + xSpacing
316387
}
317-
translateX += tileWidth + xSpacing
388+
} catch (e: RuntimeException) {
389+
// Like `ReactImageView`: the canvas throws for a bitmap that is too large to draw.
390+
canvas.restoreToCount(saveCount)
391+
FLog.w(ReactConstants.TAG, e, "Could not draw background image: %s", uri)
318392
}
319393
}
320394
}

0 commit comments

Comments
 (0)