Skip to content

Commit b30635b

Browse files
compute correct scaling (#17)
* compute correct scaling * remove set identity
1 parent e1831f8 commit b30635b

File tree

1 file changed

+46
-2
lines changed

1 file changed

+46
-2
lines changed

packages/vector_graphics/lib/vector_graphics.dart

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import 'dart:typed_data';
22
import 'dart:ui' as ui;
33
import 'dart:io';
4+
import 'dart:math' as math;
45

56
import 'package:flutter/foundation.dart';
6-
import 'package:flutter/rendering.dart';
77
import 'package:flutter/widgets.dart';
88

99
import 'package:vector_graphics_codec/vector_graphics_codec.dart';
@@ -247,7 +247,7 @@ class _RawVectorGraphicsWidget extends SingleChildRenderObjectWidget {
247247
}
248248
}
249249

250-
class _RenderVectorGraphics extends RenderProxyBox {
250+
class _RenderVectorGraphics extends RenderBox {
251251
_RenderVectorGraphics(this._pictureInfo);
252252

253253
PictureInfo get pictureInfo => _pictureInfo;
@@ -260,8 +260,52 @@ class _RenderVectorGraphics extends RenderProxyBox {
260260
markNeedsPaint();
261261
}
262262

263+
@override
264+
bool hitTestSelf(Offset position) => true;
265+
266+
@override
267+
bool get sizedByParent => true;
268+
269+
@override
270+
Size computeDryLayout(BoxConstraints constraints) {
271+
return constraints.smallest;
272+
}
273+
274+
@override
275+
bool get isRepaintBoundary => true;
276+
277+
final Matrix4 transform = Matrix4.identity();
278+
263279
@override
264280
void paint(PaintingContext context, ui.Offset offset) {
281+
if (_scaleCanvasToViewBox(transform, size, pictureInfo.size)) {
282+
context.canvas.transform(transform.storage);
283+
}
265284
context.canvas.drawPicture(_pictureInfo.picture);
266285
}
267286
}
287+
288+
bool _scaleCanvasToViewBox(
289+
Matrix4 matrix,
290+
Size desiredSize,
291+
Size pictureSize,
292+
) {
293+
if (desiredSize == pictureSize) {
294+
return false;
295+
}
296+
final double scale = math.min(
297+
desiredSize.width / pictureSize.width,
298+
desiredSize.height / pictureSize.height,
299+
);
300+
final Size scaledHalfViewBoxSize = pictureSize * scale / 2.0;
301+
final Size halfDesiredSize = desiredSize / 2.0;
302+
final Offset shift = Offset(
303+
halfDesiredSize.width - scaledHalfViewBoxSize.width,
304+
halfDesiredSize.height - scaledHalfViewBoxSize.height,
305+
);
306+
matrix
307+
..translate(shift.dx, shift.dy)
308+
..scale(scale, scale);
309+
310+
return true;
311+
}

0 commit comments

Comments
 (0)