Java Batik изменяет размер SVG на размер панели, сохраняя пропорции
Я пытаюсь отобразить изображение SVG в своем приложении Swing, так как у меня нет файла SVG, но путь, который я преобразую путь к действительному документу SVG с:
private static Document buildSVGDocument(Color svgColor, /*double svgWidth, double svgHeight,*/ String svgPath) {
DOMImplementation svgDocumentImplementation = SVGDOMImplementation.getDOMImplementation();
Document svgDocument = svgDocumentImplementation.createDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null);
Element svgDocumentElement = svgDocument.getDocumentElement();
//svgDocumentElement.setAttribute("height", String.valueOf(svgHeight));
//svgDocumentElement.setAttribute("width", String.valueOf(svgWidth));
Element svgDocumentPath = svgDocument.createElementNS(SVGDOMImplementation.SVG_NAMESPACE_URI, "path");
svgDocumentPath.setAttribute("style", String.format("fill:rgb(%s, %s, %s);", svgColor.getRed(), svgColor.getGreen(), svgColor.getBlue()));
svgDocumentPath.setAttribute("d", svgPath);
svgDocumentElement.appendChild(svgDocumentPath);
return svgDocument;
}
Затем я отображаю документ SVG на холсте из батика:
JSVGCanvas panel = new JSVGCanvas();
panel.setDocumentState(JSVGCanvas.ALWAYS_DYNAMIC);
panel.setDisableInteractions(true);
panel.setDocument(buildSVGDocument(/*etc*/));
container.add(panel, BorderLayout.WEST);
Теперь мой вопрос: как мне изменить размер SVG до размера панели, сохраняя соотношение сторон?
1 ответ
Решение
Я понял, как это сделать! Просматривая источник, я нашел метод, используемый для вычисления масштаба изображения, это:
calculateViewingTransform
Затем я реализовал простой класс для масштабирования изображения в контейнер
public class SVGCanvas extends JSVGCanvas {
private static final long serialVersionUID = 1L;
/**
* The type of scale
*/
private short svgScale;
/**
* Image padding
*/
private int svgPadding;
public SVGCanvas() {
this.svgScale = SVGPreserveAspectRatio.SVG_PRESERVEASPECTRATIO_XMIDYMAX;
this.svgPadding = 5;
}
@Override
protected AffineTransform calculateViewingTransform(String svgElementIdentifier, SVGSVGElement svgElement) {
SVGRect svgElementBounds = svgElement.getBBox();
float[] svgElementBoundsVector = new float[] {
svgElementBounds.getX(),
svgElementBounds.getY(),
svgElementBounds.getWidth(),
svgElementBounds.getHeight()
};
float svgEemenetScaleToHeight = getHeight() - svgPadding;
float svgElementScaleToWidth = getWidth() - svgPadding;
return ViewBox.getPreserveAspectRatioTransform(
svgElementBoundsVector, svgScale, true,
svgElementScaleToWidth,
svgEemenetScaleToHeight
);
}
public void setSvgScale(short svgScale) {
this.svgScale = svgScale;
}
public void setSvgPadding(int svgPadding) {
this.svgPadding = svgPadding;
}
}