Skip to content Skip to sidebar Skip to footer

How To Center And Stretch/shrink Svg Display In Twebbrowser?

In a Delphi 10.4.2 Win32 VCL Application on Windows 10 x64, I use a TWebBrowser component to display local SVG files. The TWebBrowser component has these properties: object wb1: TW

Solution 1:

To some extent this depends on the properties of the SVG image. Specifically, it depends on the values of its width, height, preserveAspectRatio, and viewBox parameters.

Consider the following example:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><svgxmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"version="1.1"width="650"height="650"viewBox="0 0 650 650"><title>A flower</title><!-- Content --></svg>

This looks like this in the TWebBrowser:

Screenshot of a VCL application form with a single TWebBrowser on it, displaying a SVG image. The SVG image doesn't fit vertically into the current view and is left-aligned.

We have several options. One thing we can do is change the SVG so it doesn't have a fixed size:

<?xml version="1.0" encoding="UTF-8" standalone="no"?><svgxmlns="http://www.w3.org/2000/svg"xmlns:xlink="http://www.w3.org/1999/xlink"version="1.1"width="100%"height="100%"viewBox="0 0 650 650"><title>A flower</title><!-- Content --></svg>

Result:

Screenshot of same window. Now the image is proportionally scaled to fix into the view. It is centred horizontally.

Another approach is to create a minimal HTML5 page containing the SVG image.

<!DOCTYPE html><html><head><metahttp-equiv="X-UA-Compatible"content="IE=edge" /></head><body><imgsrc="test.svg"style="position: absolute; top: 0; left: 0; width: 100%; height: 100%" /></body></html>

Animation of the window being resized

Here's the SVG: https://privat.rejbrand.se/flower.svg.

If the SVG file doesn't have a viewBox attribute, the approach above doesn't work. One solution -- obviously -- is then to add a viewBox attribute. For example, the OP's file has width="600" height="1050". By adding viewBox="0 0 600 1050" it becomes scalable:

<svg...width="600"height="1050"viewBox="0 0 600 1050"... >

Screen recording

Post a Comment for "How To Center And Stretch/shrink Svg Display In Twebbrowser?"