feat: radial gradient iOS (#50266)

Summary:
Adds iOS changes for radial gradient. Previous PR - https://github.com/facebook/react-native/pull/50209

## Changelog:
[IOS] [ADDED] - Radial gradient
<!-- Help reviewers and the release process by writing your own changelog entry.

Pick one each for the category and type tags:

For more details, see:
https://reactnative.dev/contributing/changelogs-in-pull-requests

Pull Request resolved: https://github.com/facebook/react-native/pull/50266

Test Plan:
- Added tests in `processBackgroundImage-test.js` in https://github.com/facebook/react-native/pull/50268
- Merge this, https://github.com/facebook/react-native/pull/50268 and check examples in `RadialGradientExample.js`

Reviewed By: joevilches

Differential Revision: D71898565

Pulled By: jorge-cab

fbshipit-source-id: ac00c7c3cc7dcbe9116c2d60dac8eb1a87153908
This commit is contained in:
nishan (o^▽^o)
2025-04-17 16:39:44 -07:00
committed by Facebook GitHub Bot
parent 867858df65
commit d7533dce1c
11 changed files with 723 additions and 236 deletions
@@ -18,6 +18,7 @@
#import <React/RCTConversions.h>
#import <React/RCTLinearGradient.h>
#import <React/RCTLocalizedString.h>
#import <React/RCTRadialGradient.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
#import <react/renderer/components/view/ViewComponentDescriptor.h>
#import <react/renderer/components/view/ViewEventEmitter.h>
@@ -1011,6 +1012,15 @@ static RCTBorderStyle RCTBorderStyleFromOutlineStyle(OutlineStyle outlineStyle)
backgroundImageLayer.zPosition = BACKGROUND_COLOR_ZPOSITION;
[self.layer addSublayer:backgroundImageLayer];
[_backgroundImageLayers addObject:backgroundImageLayer];
} else if (std::holds_alternative<RadialGradient>(backgroundImage)) {
const auto &radialGradient = std::get<RadialGradient>(backgroundImage);
CALayer *backgroundImageLayer = [RCTRadialGradient gradientLayerWithSize:self.layer.bounds.size
gradient:radialGradient];
[self shapeLayerToMatchView:backgroundImageLayer borderMetrics:borderMetrics];
backgroundImageLayer.masksToBounds = YES;
backgroundImageLayer.zPosition = BACKGROUND_COLOR_ZPOSITION;
[self.layer addSublayer:backgroundImageLayer];
[_backgroundImageLayers addObject:backgroundImageLayer];
}
}
}
@@ -0,0 +1,21 @@
/*
* 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.
*/
#include <Foundation/Foundation.h>
#include <react/renderer/graphics/ColorStop.h>
#import <vector>
NS_ASSUME_NONNULL_BEGIN
@interface RCTGradientUtils : NSObject
+ (std::vector<facebook::react::ProcessedColorStop>)getFixedColorStops:
(const std::vector<facebook::react::ColorStop> &)colorStops
gradientLineLength:(CGFloat)gradientLineLength;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,204 @@
/*
* 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.
*/
#import "RCTGradientUtils.h"
#import <React/RCTAnimationUtils.h>
#import <React/RCTConversions.h>
#import <react/utils/FloatComparison.h>
#import <vector>
using namespace facebook::react;
static std::optional<Float> resolveColorStopPosition(ValueUnit position, CGFloat gradientLineLength)
{
if (position.unit == UnitType::Point) {
return position.resolve(0.0f) / gradientLineLength;
}
if (position.unit == UnitType::Percent) {
return position.resolve(1.0f);
}
return std::nullopt;
}
// Spec: https://drafts.csswg.org/css-images-4/#coloring-gradient-line (Refer transition hint section)
// Browsers add 9 intermediate color stops when a transition hint is present
// Algorithm is referred from Blink engine
// [source](https://github.com/chromium/chromium/blob/a296b1bad6dc1ed9d751b7528f7ca2134227b828/third_party/blink/renderer/core/css/css_gradient_value.cc#L240).
static std::vector<ProcessedColorStop> processColorTransitionHints(const std::vector<ProcessedColorStop> &originalStops)
{
auto colorStops = std::vector<ProcessedColorStop>(originalStops);
int indexOffset = 0;
for (size_t i = 1; i < originalStops.size() - 1; ++i) {
// Skip if not a color hint
if (originalStops[i].color) {
continue;
}
size_t x = i + indexOffset;
if (x < 1) {
continue;
}
auto offsetLeft = colorStops[x - 1].position.value();
auto offsetRight = colorStops[x + 1].position.value();
auto offset = colorStops[x].position.value();
auto leftDist = offset - offsetLeft;
auto rightDist = offsetRight - offset;
auto totalDist = offsetRight - offsetLeft;
SharedColor leftSharedColor = colorStops[x - 1].color;
SharedColor rightSharedColor = colorStops[x + 1].color;
if (facebook::react::floatEquality(leftDist, rightDist)) {
colorStops.erase(colorStops.begin() + x);
--indexOffset;
continue;
}
if (facebook::react::floatEquality(leftDist, .0f)) {
colorStops[x].color = rightSharedColor;
continue;
}
if (facebook::react::floatEquality(rightDist, .0f)) {
colorStops[x].color = leftSharedColor;
continue;
}
std::vector<ProcessedColorStop> newStops;
newStops.reserve(9);
// Position the new color stops
if (leftDist > rightDist) {
for (int y = 0; y < 7; ++y) {
ProcessedColorStop newStop{SharedColor(), offsetLeft + leftDist * ((7.0f + y) / 13.0f)};
newStops.push_back(newStop);
}
ProcessedColorStop stop1{SharedColor(), offset + rightDist * (1.0f / 3.0f)};
ProcessedColorStop stop2{SharedColor(), offset + rightDist * (2.0f / 3.0f)};
newStops.push_back(stop1);
newStops.push_back(stop2);
} else {
ProcessedColorStop stop1{SharedColor(), offsetLeft + leftDist * (1.0f / 3.0f)};
ProcessedColorStop stop2{SharedColor(), offsetLeft + leftDist * (2.0f / 3.0f)};
newStops.push_back(stop1);
newStops.push_back(stop2);
for (int y = 0; y < 7; ++y) {
ProcessedColorStop newStop{SharedColor(), offset + rightDist * (y / 13.0f)};
newStops.push_back(newStop);
}
}
// calculate colors for the new color hints.
// The color weighting for the new color stops will be
// pointRelativeOffset^(ln(0.5)/ln(hintRelativeOffset)).
auto hintRelativeOffset = leftDist / totalDist;
const auto logRatio = log(0.5) / log(hintRelativeOffset);
auto leftColor = RCTUIColorFromSharedColor(leftSharedColor);
auto rightColor = RCTUIColorFromSharedColor(rightSharedColor);
NSArray<NSNumber *> *inputRange = @[ @0.0, @1.0 ];
NSArray<UIColor *> *outputRange = @[ leftColor, rightColor ];
for (auto &newStop : newStops) {
auto pointRelativeOffset = (newStop.position.value() - offsetLeft) / totalDist;
auto weighting = pow(pointRelativeOffset, logRatio);
if (!std::isfinite(weighting) || std::isnan(weighting)) {
continue;
}
auto interpolatedColor = RCTInterpolateColorInRange(weighting, inputRange, outputRange);
auto alpha = (interpolatedColor >> 24) & 0xFF;
auto red = (interpolatedColor >> 16) & 0xFF;
auto green = (interpolatedColor >> 8) & 0xFF;
auto blue = interpolatedColor & 0xFF;
newStop.color = facebook::react::colorFromRGBA(red, green, blue, alpha);
}
// Replace the color hint with new color stops
colorStops.erase(colorStops.begin() + x);
colorStops.insert(colorStops.begin() + x, newStops.begin(), newStops.end());
indexOffset += 8;
}
return colorStops;
}
@implementation RCTGradientUtils
// https://drafts.csswg.org/css-images-4/#color-stop-fixup
+ (std::vector<ProcessedColorStop>)getFixedColorStops:(const std::vector<ColorStop> &)colorStops
gradientLineLength:(CGFloat)gradientLineLength
{
std::vector<ProcessedColorStop> fixedColorStops(colorStops.size());
bool hasNullPositions = false;
auto maxPositionSoFar = resolveColorStopPosition(colorStops[0].position, gradientLineLength);
if (!maxPositionSoFar.has_value()) {
maxPositionSoFar = 0.0f;
}
for (size_t i = 0; i < colorStops.size(); i++) {
const auto &colorStop = colorStops[i];
auto newPosition = resolveColorStopPosition(colorStop.position, gradientLineLength);
if (!newPosition.has_value()) {
// Step 1:
// If the first color stop does not have a position,
// set its position to 0%. If the last color stop does not have a position,
// set its position to 100%.
if (i == 0) {
newPosition = 0.0f;
} else if (i == colorStops.size() - 1) {
newPosition = 1.0f;
}
}
// Step 2:
// If a color stop or transition hint has a position
// that is less than the specified position of any color stop or transition hint
// before it in the list, set its position to be equal to the
// largest specified position of any color stop or transition hint before it.
if (newPosition.has_value()) {
newPosition = std::max(newPosition.value(), maxPositionSoFar.value());
fixedColorStops[i] = ProcessedColorStop{colorStop.color, newPosition};
maxPositionSoFar = newPosition;
} else {
hasNullPositions = true;
}
}
// Step 3:
// If any color stop still does not have a position,
// then, for each run of adjacent color stops without positions,
// set their positions so that they are evenly spaced between the preceding and
// following color stops with positions.
if (hasNullPositions) {
size_t lastDefinedIndex = 0;
for (size_t i = 1; i < fixedColorStops.size(); i++) {
auto endPosition = fixedColorStops[i].position;
if (endPosition.has_value()) {
size_t unpositionedStops = i - lastDefinedIndex - 1;
if (unpositionedStops > 0) {
auto startPosition = fixedColorStops[lastDefinedIndex].position;
if (startPosition.has_value()) {
auto increment = (endPosition.value() - startPosition.value()) / (unpositionedStops + 1);
for (size_t j = 1; j <= unpositionedStops; j++) {
fixedColorStops[lastDefinedIndex + j] =
ProcessedColorStop{colorStops[lastDefinedIndex + j].color, startPosition.value() + increment * j};
}
}
}
lastDefinedIndex = i;
}
}
}
return processColorTransitionHints(fixedColorStops);
}
@end
@@ -11,6 +11,7 @@
#import <React/RCTConversions.h>
#include <react/renderer/graphics/ValueUnit.h>
#import <react/utils/FloatComparison.h>
#import "RCTGradientUtils.h"
using namespace facebook::react;
@@ -40,8 +41,8 @@ using namespace facebook::react;
CGFloat dx = endPoint.x - startPoint.x;
CGFloat dy = endPoint.y - startPoint.y;
CGFloat gradientLineLength = sqrt(dx * dx + dy * dy);
const auto processedStops = getFixedColorStops(gradient.colorStops, gradientLineLength);
const auto colorStops = processColorTransitionHints(processedStops);
const auto colorStops = [RCTGradientUtils getFixedColorStops:gradient.colorStops
gradientLineLength:gradientLineLength];
CGContextRef context = rendererContext.CGContext;
NSMutableArray *colors = [NSMutableArray array];
@@ -138,194 +139,4 @@ static CGFloat getAngleForKeyword(GradientKeyword keyword, CGSize size)
}
}
// Spec: https://drafts.csswg.org/css-images-4/#coloring-gradient-line (Refer transition hint section)
// Browsers add 9 intermediate color stops when a transition hint is present
// Algorithm is referred from Blink engine
// [source](https://github.com/chromium/chromium/blob/a296b1bad6dc1ed9d751b7528f7ca2134227b828/third_party/blink/renderer/core/css/css_gradient_value.cc#L240).
static std::vector<ProcessedColorStop> processColorTransitionHints(const std::vector<ProcessedColorStop> &originalStops)
{
auto colorStops = std::vector<ProcessedColorStop>(originalStops);
int indexOffset = 0;
for (size_t i = 1; i < originalStops.size() - 1; ++i) {
// Skip if not a color hint
if (originalStops[i].color) {
continue;
}
size_t x = i + indexOffset;
if (x < 1) {
continue;
}
auto offsetLeft = colorStops[x - 1].position.value();
auto offsetRight = colorStops[x + 1].position.value();
auto offset = colorStops[x].position.value();
auto leftDist = offset - offsetLeft;
auto rightDist = offsetRight - offset;
auto totalDist = offsetRight - offsetLeft;
SharedColor leftSharedColor = colorStops[x - 1].color;
SharedColor rightSharedColor = colorStops[x + 1].color;
if (facebook::react::floatEquality(leftDist, rightDist)) {
colorStops.erase(colorStops.begin() + x);
--indexOffset;
continue;
}
if (facebook::react::floatEquality(leftDist, .0f)) {
colorStops[x].color = rightSharedColor;
continue;
}
if (facebook::react::floatEquality(rightDist, .0f)) {
colorStops[x].color = leftSharedColor;
continue;
}
std::vector<ProcessedColorStop> newStops;
newStops.reserve(9);
// Position the new color stops
if (leftDist > rightDist) {
for (int y = 0; y < 7; ++y) {
ProcessedColorStop newStop{SharedColor(), offsetLeft + leftDist * ((7.0f + y) / 13.0f)};
newStops.push_back(newStop);
}
ProcessedColorStop stop1{SharedColor(), offset + rightDist * (1.0f / 3.0f)};
ProcessedColorStop stop2{SharedColor(), offset + rightDist * (2.0f / 3.0f)};
newStops.push_back(stop1);
newStops.push_back(stop2);
} else {
ProcessedColorStop stop1{SharedColor(), offsetLeft + leftDist * (1.0f / 3.0f)};
ProcessedColorStop stop2{SharedColor(), offsetLeft + leftDist * (2.0f / 3.0f)};
newStops.push_back(stop1);
newStops.push_back(stop2);
for (int y = 0; y < 7; ++y) {
ProcessedColorStop newStop{SharedColor(), offset + rightDist * (y / 13.0f)};
newStops.push_back(newStop);
}
}
// calculate colors for the new color hints.
// The color weighting for the new color stops will be
// pointRelativeOffset^(ln(0.5)/ln(hintRelativeOffset)).
auto hintRelativeOffset = leftDist / totalDist;
const auto logRatio = log(0.5) / log(hintRelativeOffset);
auto leftColor = RCTUIColorFromSharedColor(leftSharedColor);
auto rightColor = RCTUIColorFromSharedColor(rightSharedColor);
NSArray<NSNumber *> *inputRange = @[ @0.0, @1.0 ];
NSArray<UIColor *> *outputRange = @[ leftColor, rightColor ];
for (auto &newStop : newStops) {
auto pointRelativeOffset = (newStop.position.value() - offsetLeft) / totalDist;
auto weighting = pow(pointRelativeOffset, logRatio);
if (!std::isfinite(weighting) || std::isnan(weighting)) {
continue;
}
auto interpolatedColor = RCTInterpolateColorInRange(weighting, inputRange, outputRange);
auto alpha = (interpolatedColor >> 24) & 0xFF;
auto red = (interpolatedColor >> 16) & 0xFF;
auto green = (interpolatedColor >> 8) & 0xFF;
auto blue = interpolatedColor & 0xFF;
newStop.color = facebook::react::colorFromRGBA(red, green, blue, alpha);
}
// Replace the color hint with new color stops
colorStops.erase(colorStops.begin() + x);
colorStops.insert(colorStops.begin() + x, newStops.begin(), newStops.end());
indexOffset += 8;
}
return colorStops;
}
// https://drafts.csswg.org/css-images-4/#color-stop-fixup
static std::vector<ProcessedColorStop> getFixedColorStops(
const std::vector<ColorStop> &colorStops,
CGFloat gradientLineLength)
{
std::vector<ProcessedColorStop> fixedColorStops(colorStops.size());
bool hasNullPositions = false;
auto maxPositionSoFar = resolveColorStopPosition(colorStops[0].position, gradientLineLength);
if (!maxPositionSoFar.has_value()) {
maxPositionSoFar = 0.0f;
}
for (size_t i = 0; i < colorStops.size(); i++) {
const auto &colorStop = colorStops[i];
auto newPosition = resolveColorStopPosition(colorStop.position, gradientLineLength);
if (!newPosition.has_value()) {
// Step 1:
// If the first color stop does not have a position,
// set its position to 0%. If the last color stop does not have a position,
// set its position to 100%.
if (i == 0) {
newPosition = 0.0f;
} else if (i == colorStops.size() - 1) {
newPosition = 1.0f;
}
}
// Step 2:
// If a color stop or transition hint has a position
// that is less than the specified position of any color stop or transition hint
// before it in the list, set its position to be equal to the
// largest specified position of any color stop or transition hint before it.
if (newPosition.has_value()) {
newPosition = std::max(newPosition.value(), maxPositionSoFar.value());
fixedColorStops[i] = ProcessedColorStop{colorStop.color, newPosition};
maxPositionSoFar = newPosition;
} else {
hasNullPositions = true;
}
}
// Step 3:
// If any color stop still does not have a position,
// then, for each run of adjacent color stops without positions,
// set their positions so that they are evenly spaced between the preceding and
// following color stops with positions.
if (hasNullPositions) {
size_t lastDefinedIndex = 0;
for (size_t i = 1; i < fixedColorStops.size(); i++) {
auto endPosition = fixedColorStops[i].position;
if (endPosition.has_value()) {
size_t unpositionedStops = i - lastDefinedIndex - 1;
if (unpositionedStops > 0) {
auto startPosition = fixedColorStops[lastDefinedIndex].position;
if (startPosition.has_value()) {
auto increment = (endPosition.value() - startPosition.value()) / (unpositionedStops + 1);
for (size_t j = 1; j <= unpositionedStops; j++) {
fixedColorStops[lastDefinedIndex + j] =
ProcessedColorStop{colorStops[lastDefinedIndex + j].color, startPosition.value() + increment * j};
}
}
}
lastDefinedIndex = i;
}
}
}
return fixedColorStops;
}
static std::optional<Float> resolveColorStopPosition(ValueUnit position, CGFloat gradientLineLength)
{
if (position.unit == UnitType::Point) {
return position.resolve(0.0f) / gradientLineLength;
}
if (position.unit == UnitType::Percent) {
return position.resolve(1.0f);
}
return std::nullopt;
}
@end
@@ -0,0 +1,19 @@
/*
* 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.
*/
#import <UIKit/UIKit.h>
#import <react/renderer/components/view/ViewProps.h>
NS_ASSUME_NONNULL_BEGIN
@interface RCTRadialGradient : NSObject
+ (CALayer *)gradientLayerWithSize:(CGSize)size gradient:(const facebook::react::RadialGradient &)gradient;
@end
NS_ASSUME_NONNULL_END
@@ -0,0 +1,229 @@
/*
* 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.
*/
#import "RCTRadialGradient.h"
#import <React/RCTAnimationUtils.h>
#import <React/RCTConversions.h>
#include <react/renderer/graphics/ValueUnit.h>
#import <react/utils/FloatComparison.h>
#import "RCTGradientUtils.h"
using namespace facebook::react;
namespace {
using RadiusVector = std::pair<CGFloat, CGFloat>;
static RadiusVector RadiusToSide(
CGFloat centerX,
CGFloat centerY,
CGFloat width,
CGFloat height,
bool isCircle,
RadialGradientSize::SizeKeyword size)
{
CGFloat radiusXFromLeftSide = centerX;
CGFloat radiusYFromTopSide = centerY;
CGFloat radiusXFromRightSide = width - centerX;
CGFloat radiusYFromBottomSide = height - centerY;
CGFloat radiusX;
CGFloat radiusY;
if (size == RadialGradientSize::SizeKeyword::ClosestSide) {
radiusX = std::min(radiusXFromLeftSide, radiusXFromRightSide);
radiusY = std::min(radiusYFromTopSide, radiusYFromBottomSide);
} else {
radiusX = std::max(radiusXFromLeftSide, radiusXFromRightSide);
radiusY = std::max(radiusYFromTopSide, radiusYFromBottomSide);
}
if (isCircle) {
CGFloat radius;
if (size == RadialGradientSize::SizeKeyword::ClosestSide) {
radius = std::min(radiusX, radiusY);
} else {
radius = std::max(radiusX, radiusY);
}
return {radius, radius};
}
return {radiusX, radiusY};
}
static RadiusVector EllipseRadius(CGFloat offsetX, CGFloat offsetY, CGFloat aspectRatio)
{
if (aspectRatio == 0 || std::isinf(aspectRatio) || std::isnan(aspectRatio)) {
return {0, 0};
}
// Ellipse that passes through a point formula: (x-h)^2/a^2 + (y-k)^2/b^2 = 1
// a = semi major axis length
// b = semi minor axis length = a / aspectRatio
// x - h = offsetX
// y - k = offsetY
CGFloat a = std::sqrt(offsetX * offsetX + offsetY * offsetY * aspectRatio * aspectRatio);
return {a, a / aspectRatio};
}
static RadiusVector RadiusToCorner(
CGFloat centerX,
CGFloat centerY,
CGFloat width,
CGFloat height,
bool isCircle,
RadialGradientSize::SizeKeyword keyword)
{
std::array<CGPoint, 4> corners = {{{0, 0}, {width, 0}, {width, height}, {0, height}}};
size_t cornerIndex = 0;
CGFloat distance = hypot(centerX - corners[cornerIndex].x, centerY - corners[cornerIndex].y);
bool isClosestCorner = keyword == RadialGradientSize::SizeKeyword::ClosestCorner;
for (size_t i = 1; i < corners.size(); ++i) {
CGFloat newDistance = hypot(centerX - corners[i].x, centerY - corners[i].y);
if (isClosestCorner) {
if (newDistance < distance) {
distance = newDistance;
cornerIndex = i;
}
} else {
if (newDistance > distance) {
distance = newDistance;
cornerIndex = i;
}
}
}
if (isCircle) {
return {distance, distance};
}
// https://www.w3.org/TR/css-images-3/#typedef-radial-size
// Aspect ratio of corner size ellipse is same as the respective side size ellipse
const RadiusVector sideRadius = RadiusToSide(
centerX,
centerY,
width,
height,
false,
isClosestCorner ? RadialGradientSize::SizeKeyword::ClosestSide : RadialGradientSize::SizeKeyword::FarthestSide);
return EllipseRadius(
corners[cornerIndex].x - centerX, corners[cornerIndex].y - centerY, sideRadius.first / sideRadius.second);
}
static RadiusVector GetRadialGradientRadius(
bool isCircle,
const RadialGradientSize &size,
CGFloat centerX,
CGFloat centerY,
CGFloat width,
CGFloat height)
{
if (std::holds_alternative<RadialGradientSize::Dimensions>(size.value)) {
const auto &dimensions = std::get<RadialGradientSize::Dimensions>(size.value);
CGFloat radiusX = dimensions.x.resolve(width);
CGFloat radiusY = dimensions.y.resolve(height);
if (isCircle) {
CGFloat radius = std::max(radiusX, radiusY);
return {radius, radius};
}
return {radiusX, radiusY};
}
if (std::holds_alternative<RadialGradientSize::SizeKeyword>(size.value)) {
const auto &keyword = std::get<RadialGradientSize::SizeKeyword>(size.value);
if (keyword == RadialGradientSize::SizeKeyword::ClosestSide ||
keyword == RadialGradientSize::SizeKeyword::FarthestSide) {
return RadiusToSide(centerX, centerY, width, height, isCircle, keyword);
}
if (keyword == RadialGradientSize::SizeKeyword::ClosestCorner) {
return RadiusToCorner(centerX, centerY, width, height, isCircle, keyword);
}
}
// defaults to farthest corner
return RadiusToCorner(centerX, centerY, width, height, isCircle, RadialGradientSize::SizeKeyword::FarthestCorner);
}
} // namespace
@implementation RCTRadialGradient
+ (CALayer *)gradientLayerWithSize:(CGSize)size gradient:(const RadialGradient &)gradient
{
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:size];
UIImage *gradientImage = [renderer imageWithActions:^(UIGraphicsImageRendererContext *_Nonnull rendererContext) {
CGContextRef context = rendererContext.CGContext;
CGPoint centerPoint = CGPointMake(size.width / 2.0, size.height / 2.0);
if (gradient.position.top) {
centerPoint.y = gradient.position.top->resolve(size.height);
} else if (gradient.position.bottom) {
centerPoint.y = size.height - gradient.position.bottom->resolve(size.height);
}
if (gradient.position.left) {
centerPoint.x = gradient.position.left->resolve(size.width);
} else if (gradient.position.right) {
centerPoint.x = size.width - gradient.position.right->resolve(size.width);
}
bool isCircle = (gradient.shape == RadialGradientShape::Circle);
auto [radiusX, radiusY] =
GetRadialGradientRadius(isCircle, gradient.size, centerPoint.x, centerPoint.y, size.width, size.height);
CGFloat scale = 1.0;
if (radiusX != radiusY && gradient.shape != RadialGradientShape::Circle) {
scale = radiusX / radiusY;
CGContextSaveGState(context);
// Scale the context to make the circular gradient appear elliptical
CGContextTranslateCTM(context, centerPoint.x, centerPoint.y);
CGContextScaleCTM(context, 1.0, 1.0 / scale);
CGContextTranslateCTM(context, -centerPoint.x, -centerPoint.y);
radiusX = std::max(radiusX, radiusY * scale);
}
const auto colorStops = [RCTGradientUtils getFixedColorStops:gradient.colorStops gradientLineLength:radiusX];
NSMutableArray *colors = [NSMutableArray array];
CGFloat locations[colorStops.size()];
for (size_t i = 0; i < colorStops.size(); ++i) {
const auto &colorStop = colorStops[i];
CGColorRef cgColor = RCTCreateCGColorRefFromSharedColor(colorStop.color);
[colors addObject:(__bridge id)cgColor];
locations[i] = std::max(std::min(colorStop.position.value(), 1.0), 0.0);
}
CGGradientRef cgGradient = CGGradientCreateWithColors(NULL, (__bridge CFArrayRef)colors, locations);
CGContextDrawRadialGradient(
context,
cgGradient,
centerPoint,
0,
centerPoint,
radiusX,
kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
// Restore the context state if we scaled it
if (radiusX != radiusY && gradient.shape != RadialGradientShape::Circle) {
CGContextRestoreGState(context);
}
for (id color in colors) {
CGColorRelease((__bridge CGColorRef)color);
}
CGGradientRelease(cgGradient);
}];
CALayer *gradientLayer = [CALayer layer];
gradientLayer.contents = (__bridge id)gradientImage.CGImage;
return gradientLayer;
}
@end
@@ -1180,6 +1180,44 @@ inline void fromRawValue(
}
std::string type = (std::string)(typeIt->second);
std::vector<ColorStop> colorStops;
auto colorStopsIt = rawBackgroundImageMap.find("colorStops");
if (colorStopsIt != rawBackgroundImageMap.end() &&
colorStopsIt->second.hasType<std::vector<RawValue>>()) {
auto rawColorStops =
static_cast<std::vector<RawValue>>(colorStopsIt->second);
for (const auto& stop : rawColorStops) {
if (stop.hasType<std::unordered_map<std::string, RawValue>>()) {
auto stopMap =
static_cast<std::unordered_map<std::string, RawValue>>(stop);
auto positionIt = stopMap.find("position");
auto colorIt = stopMap.find("color");
if (positionIt != stopMap.end() && colorIt != stopMap.end()) {
ColorStop colorStop;
if (positionIt->second.hasValue()) {
auto valueUnit = toValueUnit(positionIt->second);
if (!valueUnit) {
result = {};
return;
}
colorStop.position = valueUnit;
}
if (colorIt->second.hasValue()) {
fromRawValue(
context.contextContainer,
context.surfaceId,
colorIt->second,
colorStop.color);
}
colorStops.push_back(colorStop);
}
}
}
}
if (type == "linearGradient") {
LinearGradient linearGradient;
@@ -1213,43 +1251,88 @@ inline void fromRawValue(
}
}
auto colorStopsIt = rawBackgroundImageMap.find("colorStops");
if (colorStopsIt != rawBackgroundImageMap.end() &&
colorStopsIt->second.hasType<std::vector<RawValue>>()) {
auto rawColorStops =
static_cast<std::vector<RawValue>>(colorStopsIt->second);
if (colorStops.empty()) {
linearGradient.colorStops = colorStops;
}
for (const auto& stop : rawColorStops) {
if (stop.hasType<std::unordered_map<std::string, RawValue>>()) {
auto stopMap =
static_cast<std::unordered_map<std::string, RawValue>>(stop);
auto positionIt = stopMap.find("position");
auto colorIt = stopMap.find("color");
backgroundImage.emplace_back(std::move(linearGradient));
} else if (type == "radialGradient") {
RadialGradient radialGradient;
auto shapeIt = rawBackgroundImageMap.find("shape");
if (shapeIt != rawBackgroundImageMap.end() &&
shapeIt->second.hasType<std::string>()) {
auto shape = (std::string)(shapeIt->second);
radialGradient.shape = shape == "circle" ? RadialGradientShape::Circle
: RadialGradientShape::Ellipse;
}
if (positionIt != stopMap.end() && colorIt != stopMap.end()) {
ColorStop colorStop;
if (positionIt->second.hasValue()) {
auto valueUnit = toValueUnit(positionIt->second);
if (!valueUnit) {
result = {};
return;
}
colorStop.position = valueUnit;
}
if (colorIt->second.hasValue()) {
fromRawValue(
context.contextContainer,
context.surfaceId,
colorIt->second,
colorStop.color);
}
linearGradient.colorStops.push_back(colorStop);
}
auto sizeIt = rawBackgroundImageMap.find("size");
if (sizeIt != rawBackgroundImageMap.end()) {
if (sizeIt->second.hasType<std::string>()) {
auto sizeStr = (std::string)(sizeIt->second);
if (sizeStr == "closest-side") {
radialGradient.size.value =
RadialGradientSize::SizeKeyword::ClosestSide;
} else if (sizeStr == "farthest-side") {
radialGradient.size.value =
RadialGradientSize::SizeKeyword::FarthestSide;
} else if (sizeStr == "closest-corner") {
radialGradient.size.value =
RadialGradientSize::SizeKeyword::ClosestCorner;
} else if (sizeStr == "farthest-corner") {
radialGradient.size.value =
RadialGradientSize::SizeKeyword::FarthestCorner;
}
} else if (sizeIt->second
.hasType<std::unordered_map<std::string, RawValue>>()) {
auto sizeMap = static_cast<std::unordered_map<std::string, RawValue>>(
sizeIt->second);
auto xIt = sizeMap.find("x");
auto yIt = sizeMap.find("y");
if (xIt != sizeMap.end() && yIt != sizeMap.end()) {
RadialGradientSize sizeObj;
sizeObj.value = RadialGradientSize::Dimensions{
toValueUnit(xIt->second), toValueUnit(yIt->second)};
radialGradient.size = sizeObj;
}
}
auto positionIt = rawBackgroundImageMap.find("position");
if (positionIt != rawBackgroundImageMap.end() &&
positionIt->second
.hasType<std::unordered_map<std::string, RawValue>>()) {
auto positionMap =
static_cast<std::unordered_map<std::string, RawValue>>(
positionIt->second);
auto topIt = positionMap.find("top");
auto bottomIt = positionMap.find("bottom");
auto leftIt = positionMap.find("left");
auto rightIt = positionMap.find("right");
if (topIt != positionMap.end()) {
auto topValue = toValueUnit(topIt->second);
radialGradient.position.top = topValue;
} else if (bottomIt != positionMap.end()) {
auto bottomValue = toValueUnit(bottomIt->second);
radialGradient.position.bottom = bottomValue;
}
if (leftIt != positionMap.end()) {
auto leftValue = toValueUnit(leftIt->second);
radialGradient.position.left = leftValue;
} else if (rightIt != positionMap.end()) {
auto rightValue = toValueUnit(rightIt->second);
radialGradient.position.right = rightValue;
}
}
}
backgroundImage.push_back(std::move(linearGradient));
if (colorStops.empty()) {
radialGradient.colorStops = colorStops;
}
backgroundImage.emplace_back(std::move(radialGradient));
}
}
@@ -9,10 +9,11 @@
#include <react/renderer/graphics/ColorComponents.h>
#include <react/renderer/graphics/LinearGradient.h>
#include <react/renderer/graphics/RadialGradient.h>
#include <vector>
namespace facebook::react {
using BackgroundImage = std::variant<LinearGradient>;
using BackgroundImage = std::variant<LinearGradient, RadialGradient>;
}; // namespace facebook::react
@@ -0,0 +1,28 @@
/*
* 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.
*/
#pragma once
#include <react/renderer/graphics/Color.h>
#include <react/renderer/graphics/Float.h>
#include <react/renderer/graphics/ValueUnit.h>
namespace facebook::react {
struct ColorStop {
bool operator==(const ColorStop& other) const = default;
SharedColor color;
ValueUnit position;
};
struct ProcessedColorStop {
bool operator==(const ProcessedColorStop& other) const = default;
SharedColor color;
std::optional<Float> position;
};
}; // namespace facebook::react
@@ -7,6 +7,7 @@
#pragma once
#include <react/renderer/graphics/ColorStop.h>
#include <react/renderer/graphics/Float.h>
#include <react/renderer/graphics/ValueUnit.h>
#include <string>
@@ -33,18 +34,6 @@ struct GradientDirection {
}
};
struct ColorStop {
bool operator==(const ColorStop& other) const = default;
SharedColor color;
ValueUnit position;
};
struct ProcessedColorStop {
bool operator==(const ProcessedColorStop& other) const = default;
SharedColor color;
std::optional<Float> position;
};
struct LinearGradient {
GradientDirection direction;
std::vector<ColorStop> colorStops;
@@ -0,0 +1,92 @@
/*
* 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.
*/
#pragma once
#include <react/renderer/graphics/ColorStop.h>
#include <react/renderer/graphics/Float.h>
#include <react/renderer/graphics/ValueUnit.h>
#include <optional>
#include <string>
#include <variant>
#include <vector>
namespace facebook::react {
enum class RadialGradientShape { Circle, Ellipse };
struct RadialGradientSize {
enum class SizeKeyword {
ClosestSide,
FarthestSide,
ClosestCorner,
FarthestCorner
};
struct Dimensions {
ValueUnit x;
ValueUnit y;
bool operator==(const Dimensions& other) const {
return x == other.x && y == other.y;
}
bool operator!=(const Dimensions& other) const {
return !(*this == other);
}
};
std::variant<SizeKeyword, Dimensions> value;
bool operator==(const RadialGradientSize& other) const {
if (std::holds_alternative<SizeKeyword>(value) &&
std::holds_alternative<SizeKeyword>(other.value)) {
return std::get<SizeKeyword>(value) == std::get<SizeKeyword>(other.value);
} else if (
std::holds_alternative<Dimensions>(value) &&
std::holds_alternative<Dimensions>(other.value)) {
return std::get<Dimensions>(value) == std::get<Dimensions>(other.value);
}
return false;
}
bool operator!=(const RadialGradientSize& other) const {
return !(*this == other);
}
};
struct RadialGradientPosition {
std::optional<ValueUnit> top;
std::optional<ValueUnit> left;
std::optional<ValueUnit> right;
std::optional<ValueUnit> bottom;
bool operator==(const RadialGradientPosition& other) const {
return top == other.top && left == other.left && right == other.right &&
bottom == other.bottom;
}
bool operator!=(const RadialGradientPosition& other) const {
return !(*this == other);
}
};
struct RadialGradient {
RadialGradientShape shape;
RadialGradientSize size;
RadialGradientPosition position;
std::vector<ColorStop> colorStops;
bool operator==(const RadialGradient& other) const {
return shape == other.shape && size == other.size &&
position == other.position && colorStops == other.colorStops;
}
bool operator!=(const RadialGradient& other) const {
return !(*this == other);
}
};
}; // namespace facebook::react