Skip to content

Commit 9f2f8a4

Browse files
koji-1009justinmcvictorsanni
authored
Add useLogicalPixels to ResizeImage for logical pixel cache sizing (flutter#184549)
fix flutter#56239 Add `useLogicalPixels` to `ResizeImage` and `useLogicalCacheSize` to `Image.{network, file, asset, memory}` and `FadeInImage.{memoryNetwork, assetNetwork}` constructors. When `true`, the cache dimensions are interpreted as logical pixels rather than physical pixels, so the cached resolution follows the surrounding device pixel ratio without requiring `BuildContext` at the call site. Default is `false`; existing callers are unaffected. <img width="300" alt="example" src="https://github.com/user-attachments/assets/43c10cd6-8b8e-4c87-93fd-b2be80030af2" /> <details> <summary>app(lib/main.dart)</summary> ```dart import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @OverRide Widget build(BuildContext context) { return MaterialApp(home: const MyWidget()); } } class MyWidget extends StatelessWidget { const MyWidget({super.key}); @OverRide Widget build(BuildContext context) { final dpr = MediaQuery.devicePixelRatioOf(context); const url = 'https://images.unsplash.com/photo-1550613097-fe6c2c321cd3' '?auto=format&fit=crop&w=1200&q=80'; return Scaffold( appBar: AppBar(title: Text('devicePixelRatio: $dpr')), body: Center( child: Column( spacing: 8, children: [ const Text('No cacheWidth (reference)'), Image.network(url, width: 300, fit: BoxFit.cover), const Text('cacheWidth: 300, useLogicalCacheSize: false'), Image.network(url, width: 300, fit: BoxFit.cover, cacheWidth: 300), const Text('cacheWidth: 300, useLogicalCacheSize: true'), Image.network( url, width: 300, fit: BoxFit.cover, cacheWidth: 300, useLogicalCacheSize: true, ), ], ), ), ); } } ``` </details> ## Pre-launch Checklist - [x] I read the [Contributor Guide] and followed the process outlined there for submitting PRs. - [x] I read the [AI contribution guidelines] and understand my responsibilities, or I am not using AI tools. - [x] I read the [Tree Hygiene] wiki page, which explains my responsibilities. - [x] I read and followed the [Flutter Style Guide], including [Features we expect every widget to implement]. - [x] I signed the [CLA]. - [x] I listed at least one issue that this PR fixes in the description above. - [x] I updated/added relevant documentation (doc comments with `///`). - [x] I added new tests to check the change I am making, or this PR is [test-exempt]. - [x] I followed the [breaking change policy] and added [Data Driven Fixes] where supported. - [x] All existing and new tests are passing. If you need help, consider asking for advice on the #hackers-new channel on [Discord]. **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. <!-- Links --> [Contributor Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#overview [AI contribution guidelines]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#ai-contribution-guidelines [Tree Hygiene]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md [test-exempt]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#tests [Flutter Style Guide]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md [Features we expect every widget to implement]: https://github.com/flutter/flutter/blob/main/docs/contributing/Style-guide-for-Flutter-repo.md#features-we-expect-every-widget-to-implement [CLA]: https://cla.developers.google.com/ [flutter/tests]: https://github.com/flutter/tests [breaking change policy]: https://github.com/flutter/flutter/blob/main/docs/contributing/Tree-hygiene.md#handling-breaking-changes [Discord]: https://github.com/flutter/flutter/blob/main/docs/contributing/Chat.md [Data Driven Fixes]: https://github.com/flutter/flutter/blob/main/docs/contributing/Data-driven-Fixes.md --------- Co-authored-by: Justin McCandless <[email protected]> Co-authored-by: Victor Sanni <[email protected]>
1 parent 65a3f54 commit 9f2f8a4

6 files changed

Lines changed: 305 additions & 22 deletions

File tree

‎packages/flutter/lib/src/painting/image_provider.dart‎

Lines changed: 59 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1263,23 +1263,28 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
12631263
/// use less memory if resized to a size smaller than the native size.
12641264
///
12651265
/// At least one of `width` and `height` must be non-null.
1266+
///
1267+
/// {@macro flutter.painting.ResizeImage.useLogicalSize}
12661268
const ResizeImage(
12671269
this.imageProvider, {
12681270
this.width,
12691271
this.height,
12701272
this.policy = ResizeImagePolicy.exact,
12711273
this.allowUpscaling = false,
1274+
this.useLogicalSize = false,
12721275
}) : assert(width != null || height != null);
12731276

12741277
/// The [ImageProvider] that this class wraps.
12751278
final ImageProvider imageProvider;
12761279

1277-
/// The width the image should decode to and cache.
1280+
/// The width the image should decode to and cache, in physical pixels unless
1281+
/// [useLogicalSize] is true.
12781282
///
12791283
/// At least one of this and [height] must be non-null.
12801284
final int? width;
12811285

1282-
/// The height the image should decode to and cache.
1286+
/// The height the image should decode to and cache, in physical pixels unless
1287+
/// [useLogicalSize] is true.
12831288
///
12841289
/// At least one of this and [width] must be non-null.
12851290
final int? height;
@@ -1298,18 +1303,41 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
12981303
/// to use an appropriate [Image.fit].
12991304
final bool allowUpscaling;
13001305

1306+
/// {@template flutter.painting.ResizeImage.useLogicalSize}
1307+
/// Whether [width] and [height] are interpreted as logical pixels.
1308+
///
1309+
/// When `false` (the default), [width] and [height] are treated as physical
1310+
/// pixels. On high-density displays, this can result in images being decoded
1311+
/// at fewer pixels than the screen can render, producing lower-quality output.
1312+
/// When `true`, [width] and [height] are multiplied by the device pixel ratio
1313+
/// from the current [ImageConfiguration], so the image is decoded at the
1314+
/// resolution that matches the rendered display.
1315+
///
1316+
/// Typically in the framework, pixel dimensions are interpreted as logical
1317+
/// rather than physical. However, this defaults to physical for backwards
1318+
/// compatibility.
1319+
/// {@endtemplate}
1320+
final bool useLogicalSize;
1321+
13011322
/// Composes the `provider` in a [ResizeImage] only when `cacheWidth` and
13021323
/// `cacheHeight` are not both null.
13031324
///
13041325
/// When `cacheWidth` and `cacheHeight` are both null, this will return the
1305-
/// `provider` directly.
1326+
/// `provider` directly. If `useLogicalSize` is true, the cache dimensions
1327+
/// are interpreted as logical pixels instead of physical pixels.
13061328
static ImageProvider<Object> resizeIfNeeded(
13071329
int? cacheWidth,
13081330
int? cacheHeight,
1309-
ImageProvider<Object> provider,
1310-
) {
1331+
ImageProvider<Object> provider, {
1332+
bool useLogicalSize = false,
1333+
}) {
13111334
if (cacheWidth != null || cacheHeight != null) {
1312-
return ResizeImage(provider, width: cacheWidth, height: cacheHeight);
1335+
return ResizeImage(
1336+
provider,
1337+
width: cacheWidth,
1338+
height: cacheHeight,
1339+
useLogicalSize: useLogicalSize,
1340+
);
13131341
}
13141342
return provider;
13151343
}
@@ -1333,8 +1361,8 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
13331361
);
13341362
return decode(
13351363
buffer,
1336-
cacheWidth: width,
1337-
cacheHeight: height,
1364+
cacheWidth: key._width,
1365+
cacheHeight: key._height,
13381366
allowUpscaling: this.allowUpscaling,
13391367
);
13401368
}
@@ -1352,6 +1380,9 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
13521380

13531381
@override
13541382
ImageStreamCompleter loadImage(ResizeImageKey key, ImageDecoderCallback decode) {
1383+
final int? effectiveWidth = key._width;
1384+
final int? effectiveHeight = key._height;
1385+
13551386
Future<ui.Codec> decodeResize(
13561387
ui.ImmutableBuffer buffer, {
13571388
ui.TargetImageSizeCallback? getTargetSize,
@@ -1366,8 +1397,8 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
13661397
getTargetSize: (int intrinsicWidth, int intrinsicHeight) {
13671398
switch (policy) {
13681399
case ResizeImagePolicy.exact:
1369-
int? targetWidth = width;
1370-
int? targetHeight = height;
1400+
var targetWidth = effectiveWidth;
1401+
var targetHeight = effectiveHeight;
13711402

13721403
if (!allowUpscaling) {
13731404
if (targetWidth != null && targetWidth > intrinsicWidth) {
@@ -1381,8 +1412,8 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
13811412
return ui.TargetImageSize(width: targetWidth, height: targetHeight);
13821413
case ResizeImagePolicy.fit:
13831414
final double aspectRatio = intrinsicWidth / intrinsicHeight;
1384-
final int maxWidth = width ?? intrinsicWidth;
1385-
final int maxHeight = height ?? intrinsicHeight;
1415+
final int maxWidth = effectiveWidth ?? intrinsicWidth;
1416+
final int maxHeight = effectiveHeight ?? intrinsicHeight;
13861417
var targetWidth = intrinsicWidth;
13871418
var targetHeight = intrinsicHeight;
13881419

@@ -1397,12 +1428,12 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
13971428
}
13981429

13991430
if (allowUpscaling) {
1400-
if (width == null) {
1401-
assert(height != null);
1402-
targetHeight = height!;
1431+
if (effectiveWidth == null) {
1432+
assert(effectiveHeight != null);
1433+
targetHeight = effectiveHeight!;
14031434
targetWidth = (targetHeight * aspectRatio).floor();
1404-
} else if (height == null) {
1405-
targetWidth = width!;
1435+
} else if (effectiveHeight == null) {
1436+
targetWidth = effectiveWidth;
14061437
targetHeight = targetWidth ~/ aspectRatio;
14071438
} else {
14081439
final int derivedMaxWidth = (maxHeight * aspectRatio).floor();
@@ -1443,6 +1474,9 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
14431474

14441475
@override
14451476
Future<ResizeImageKey> obtainKey(ImageConfiguration configuration) {
1477+
final double devicePixelRatio = useLogicalSize ? (configuration.devicePixelRatio ?? 1.0) : 1.0;
1478+
final int? effectiveWidth = width != null ? (width! * devicePixelRatio).ceil() : null;
1479+
final int? effectiveHeight = height != null ? (height! * devicePixelRatio).ceil() : null;
14461480
Completer<ResizeImageKey>? completer;
14471481
// If the imageProvider.obtainKey future is synchronous, then we will be able to fill in result with
14481482
// a value before completer is initialized below.
@@ -1452,11 +1486,13 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
14521486
// This future has completed synchronously (completer was never assigned),
14531487
// so we can directly create the synchronous result to return.
14541488
result = SynchronousFuture<ResizeImageKey>(
1455-
ResizeImageKey._(key, policy, width, height, allowUpscaling),
1489+
ResizeImageKey._(key, policy, effectiveWidth, effectiveHeight, allowUpscaling),
14561490
);
14571491
} else {
14581492
// This future did not synchronously complete.
1459-
completer.complete(ResizeImageKey._(key, policy, width, height, allowUpscaling));
1493+
completer.complete(
1494+
ResizeImageKey._(key, policy, effectiveWidth, effectiveHeight, allowUpscaling),
1495+
);
14601496
}
14611497
});
14621498
if (result != null) {
@@ -1481,11 +1517,13 @@ class ResizeImage extends ImageProvider<ResizeImageKey> {
14811517
width == other.width &&
14821518
height == other.height &&
14831519
policy == other.policy &&
1484-
allowUpscaling == other.allowUpscaling;
1520+
allowUpscaling == other.allowUpscaling &&
1521+
useLogicalSize == other.useLogicalSize;
14851522
}
14861523

14871524
@override
1488-
int get hashCode => Object.hash(imageProvider, width, height, policy, allowUpscaling);
1525+
int get hashCode =>
1526+
Object.hash(imageProvider, width, height, policy, allowUpscaling, useLogicalSize);
14891527
}
14901528

14911529
/// The strategy for [Image.network] and [NetworkImage] to decide whether to

‎packages/flutter/lib/src/widgets/fade_in_image.dart‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,11 @@ class FadeInImage extends StatefulWidget {
116116
/// and [height] regardless of these parameters. These parameters are primarily
117117
/// intended to reduce the memory usage of [ImageCache].
118118
///
119+
/// If [useLogicalCacheSize] is true, the cache dimensions are interpreted
120+
/// as logical pixels instead of physical pixels. Set this to true when
121+
/// the cache dimensions describe the image's on-screen size in logical
122+
/// pixels. The flag applies to both the placeholder and the image.
123+
///
119124
/// The [placeholder], [image], [placeholderScale], [imageScale],
120125
/// [fadeOutDuration], [fadeOutCurve], [fadeInDuration], [fadeInCurve],
121126
/// [alignment], [repeat], and [matchTextDirection] arguments must not be
@@ -158,15 +163,18 @@ class FadeInImage extends StatefulWidget {
158163
int? placeholderCacheHeight,
159164
int? imageCacheWidth,
160165
int? imageCacheHeight,
166+
bool useLogicalCacheSize = false,
161167
}) : placeholder = ResizeImage.resizeIfNeeded(
162168
placeholderCacheWidth,
163169
placeholderCacheHeight,
164170
MemoryImage(placeholder, scale: placeholderScale),
171+
useLogicalSize: useLogicalCacheSize,
165172
),
166173
image = ResizeImage.resizeIfNeeded(
167174
imageCacheWidth,
168175
imageCacheHeight,
169176
NetworkImage(image, scale: imageScale),
177+
useLogicalSize: useLogicalCacheSize,
170178
);
171179

172180
/// Creates a widget that uses a placeholder image stored in an asset bundle
@@ -190,6 +198,11 @@ class FadeInImage extends StatefulWidget {
190198
/// and [height] regardless of these parameters. These parameters are primarily
191199
/// intended to reduce the memory usage of [ImageCache].
192200
///
201+
/// If [useLogicalCacheSize] is true, the cache dimensions are interpreted
202+
/// as logical pixels instead of physical pixels. Set this to true when
203+
/// the cache dimensions describe the image's on-screen size in logical
204+
/// pixels. The flag applies to both the placeholder and the image.
205+
///
193206
/// See also:
194207
///
195208
/// * [Image.asset], which has more details about loading images from
@@ -228,21 +241,25 @@ class FadeInImage extends StatefulWidget {
228241
int? placeholderCacheHeight,
229242
int? imageCacheWidth,
230243
int? imageCacheHeight,
244+
bool useLogicalCacheSize = false,
231245
}) : placeholder = placeholderScale != null
232246
? ResizeImage.resizeIfNeeded(
233247
placeholderCacheWidth,
234248
placeholderCacheHeight,
235249
ExactAssetImage(placeholder, bundle: bundle, scale: placeholderScale),
250+
useLogicalSize: useLogicalCacheSize,
236251
)
237252
: ResizeImage.resizeIfNeeded(
238253
placeholderCacheWidth,
239254
placeholderCacheHeight,
240255
AssetImage(placeholder, bundle: bundle),
256+
useLogicalSize: useLogicalCacheSize,
241257
),
242258
image = ResizeImage.resizeIfNeeded(
243259
imageCacheWidth,
244260
imageCacheHeight,
245261
NetworkImage(image, scale: imageScale),
262+
useLogicalSize: useLogicalCacheSize,
246263
);
247264

248265
/// Image displayed while the target [image] is loading.

‎packages/flutter/lib/src/widgets/image.dart‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -405,6 +405,11 @@ class Image extends StatefulWidget {
405405
/// regardless of these parameters. These parameters are primarily intended
406406
/// to reduce the memory usage of [ImageCache].
407407
///
408+
/// If [useLogicalCacheSize] is true, [cacheWidth] and [cacheHeight] are
409+
/// interpreted as logical pixels instead of physical pixels. Set this to
410+
/// true when [cacheWidth] and [cacheHeight] describe the image's on-screen
411+
/// size in logical pixels.
412+
///
408413
/// In the case where the network image is on the Web platform, the [cacheWidth]
409414
/// and [cacheHeight] parameters are ignored as the web engine delegates
410415
/// image decoding to the web which does not support custom decode sizes.
@@ -467,6 +472,7 @@ class Image extends StatefulWidget {
467472
Map<String, String>? headers,
468473
int? cacheWidth,
469474
int? cacheHeight,
475+
bool useLogicalCacheSize = false,
470476
WebHtmlElementStrategy webHtmlElementStrategy = WebHtmlElementStrategy.never,
471477
}) : image = ResizeImage.resizeIfNeeded(
472478
cacheWidth,
@@ -477,6 +483,7 @@ class Image extends StatefulWidget {
477483
headers: headers,
478484
webHtmlElementStrategy: webHtmlElementStrategy,
479485
),
486+
useLogicalSize: useLogicalCacheSize,
480487
),
481488
assert(cacheWidth == null || cacheWidth > 0),
482489
assert(cacheHeight == null || cacheHeight > 0);
@@ -505,6 +512,11 @@ class Image extends StatefulWidget {
505512
/// regardless of these parameters. These parameters are primarily intended
506513
/// to reduce the memory usage of [ImageCache].
507514
///
515+
/// If [useLogicalCacheSize] is true, [cacheWidth] and [cacheHeight] are
516+
/// interpreted as logical pixels instead of physical pixels. Set this to
517+
/// true when [cacheWidth] and [cacheHeight] describe the image's on-screen
518+
/// size in logical pixels.
519+
///
508520
/// Loading an image from a file creates an in memory copy of the file,
509521
/// which is retained in the [ImageCache]. The underlying file is not
510522
/// monitored for changes. If it does change, the application should evict
@@ -536,13 +548,19 @@ class Image extends StatefulWidget {
536548
this.filterQuality = FilterQuality.medium,
537549
int? cacheWidth,
538550
int? cacheHeight,
551+
bool useLogicalCacheSize = false,
539552
}) : // FileImage is not supported on Flutter Web therefore neither this method.
540553
assert(
541554
!kIsWeb,
542555
'Image.file is not supported on Flutter Web. '
543556
'Consider using either Image.asset or Image.network instead.',
544557
),
545-
image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, FileImage(file, scale: scale)),
558+
image = ResizeImage.resizeIfNeeded(
559+
cacheWidth,
560+
cacheHeight,
561+
FileImage(file, scale: scale),
562+
useLogicalSize: useLogicalCacheSize,
563+
),
546564
loadingBuilder = null,
547565
assert(cacheWidth == null || cacheWidth > 0),
548566
assert(cacheHeight == null || cacheHeight > 0);
@@ -585,6 +603,11 @@ class Image extends StatefulWidget {
585603
/// regardless of these parameters. These parameters are primarily intended
586604
/// to reduce the memory usage of [ImageCache].
587605
///
606+
/// If [useLogicalCacheSize] is true, [cacheWidth] and [cacheHeight] are
607+
/// interpreted as logical pixels instead of physical pixels. Set this to
608+
/// true when [cacheWidth] and [cacheHeight] describe the image's on-screen
609+
/// size in logical pixels.
610+
///
588611
/// Either the [width] and [height] arguments should be specified, or the
589612
/// widget should be placed in a context that sets tight layout constraints.
590613
/// Otherwise, the image dimensions will change as the image is loaded, which
@@ -699,12 +722,14 @@ class Image extends StatefulWidget {
699722
this.filterQuality = FilterQuality.medium,
700723
int? cacheWidth,
701724
int? cacheHeight,
725+
bool useLogicalCacheSize = false,
702726
}) : image = ResizeImage.resizeIfNeeded(
703727
cacheWidth,
704728
cacheHeight,
705729
scale != null
706730
? ExactAssetImage(name, bundle: bundle, scale: scale, package: package)
707731
: AssetImage(name, bundle: bundle, package: package),
732+
useLogicalSize: useLogicalCacheSize,
708733
),
709734
loadingBuilder = null,
710735
assert(cacheWidth == null || cacheWidth > 0),
@@ -738,6 +763,11 @@ class Image extends StatefulWidget {
738763
/// will be rendered to the constraints of the layout or [width] and [height]
739764
/// regardless of these parameters. These parameters are primarily intended
740765
/// to reduce the memory usage of [ImageCache].
766+
///
767+
/// If [useLogicalCacheSize] is true, [cacheWidth] and [cacheHeight] are
768+
/// interpreted as logical pixels instead of physical pixels. Set this to
769+
/// true when [cacheWidth] and [cacheHeight] describe the image's on-screen
770+
/// size in logical pixels.
741771
Image.memory(
742772
Uint8List bytes, {
743773
super.key,
@@ -761,10 +791,12 @@ class Image extends StatefulWidget {
761791
this.filterQuality = FilterQuality.medium,
762792
int? cacheWidth,
763793
int? cacheHeight,
794+
bool useLogicalCacheSize = false,
764795
}) : image = ResizeImage.resizeIfNeeded(
765796
cacheWidth,
766797
cacheHeight,
767798
MemoryImage(bytes, scale: scale),
799+
useLogicalSize: useLogicalCacheSize,
768800
),
769801
loadingBuilder = null,
770802
assert(cacheWidth == null || cacheWidth > 0),

0 commit comments

Comments
 (0)