如何从黑白背景下视图的RGB值获取单一RGB与透明度值——iOS键盘扩展明暗模式适配
Got it, let’s work through this problem together. You need one semi-transparent gray color that looks exactly like RGB(150,150,150) on a white (light mode) background and RGB(107,107,107) on a black (dark mode) background. Here’s how to calculate it properly:
Step 1: Recall the Alpha Blending Formula
iOS uses standard alpha blending for colors. For grayscale (all RGB channels identical), the resulting color on a background follows this rule for each channel:
resulting_channel = (foreground_channel * opacity) + (background_channel * (1 - opacity))
Where:
opacityis the foreground color’s opacity (0 = fully transparent, 1 = fully opaque)foreground_channelis the RGB value of your semi-transparent color (we’ll call thisXsince all channels are the same)background_channelis 255 for white (light mode) and 0 for black (dark mode)
Step 2: Set Up Equations for Both Backgrounds
We know our target results, so let’s write two equations:
- Light mode (white background): We need the result to be 150
X * opacity + 255 * (1 - opacity) = 150 - Dark mode (black background): We need the result to be 107
X * opacity + 0 * (1 - opacity) = 107
Step 3: Solve for Opacity and RGB Value
From the dark mode equation, we get X * opacity = 107 (let’s call this our baseline equation).
Substitute this into the light mode equation:
107 + 255*(1 - opacity) = 150
Rearrange to solve for opacity:
255*(1 - opacity) = 150 - 107 = 43 1 - opacity = 43 / 255 ≈ 0.1686 opacity ≈ 0.8314 (or ~83% opacity)
Now plug this opacity back into the baseline equation to find X:
X = 107 / 0.8314 ≈ 128.7
Round to the nearest integer: X = 129
Step 4: Final Color Values
Your single semi-transparent color is:
- RGB:
(129, 129, 129) - Opacity:
~0.83(use the decimal value 0.83 in your code)
Step 5: Double-Check the Results
- On white background:
129*0.83 + 255*(1-0.83) ≈ 107.07 + 43.35 ≈ 150.42(nearly identical to your target 150) - On black background:
129*0.83 ≈ 107.07(almost exactly your target 107)
This color will perfectly match the iOS keyboard key appearance in both light and dark modes with a single set of values.
内容的提问来源于stack exchange,提问作者ibayramli

