[英]How to convert an SVG file to Base64String/JPG/PNG in NativeScript to use in Img Tag?
我正在嘗試在我的 NativeScript 應用程序上顯示 SVG 圖像。 我發現有多種方法可以做到這一點。
我發現的第一種方法是從 SVG 轉換為 Base64String。 然后可以將該 Base64String 轉換為 PNG/JPG 顯示,如下所示:
let baseString = "someBaseString";
let imageFromBase64String = ImageSource.fromBase64Sync(baseString);
但問題是,這只有在我們已經有一個由 SVG 文件制成的 Base64String 時才有效,而且我首先找不到從 SVG 轉換為 Base64String 的方法。
我發現的第二種方法如下,使用URL.createObject()
if (svgDoc,= null || svgDoc:= undefined) { let blob = new Blob([svgDoc]; {type. 'image/svg+xml'}); let url = URL.createObjectURL(blob). let sanitzed = this;sanitizer.bypassSecurityTrustUrl(url); }
然后在 <img src""> 標簽中使用創建的sanitized
鏈接。 但問題是這僅適用於 Angular Web 應用程序,而不適用於 NativeScript。
任何類型的信息都會有所幫助。 先感謝您:)
在 nativescript 圖像應該通過 http 的getImage方法請求。
我認為使用將 svg 轉換為 canvas 的庫可以獲得最好的結果,請參閱 DanGreen 的這個。 另一種選擇是 this another one this link 。
我用這個 stackblitz中的兩種方法做了一個簡單的例子
如果你有一個 svg 和一個兩個 canvas
<svg #svg...>
</svg>
<canvas #canvas></canvas>
<canvas #canvas2></canvas>
@ViewChild('svg', { static: true }) svg;
@ViewChild('canvas', { static: true }) canvas;
@ViewChild('canvas2', { static: true }) canvas2;
v: any;
async ngOnInit() {
const svgElement = this.svg.nativeElement;
const { width, height } = svgElement.getBBox();
const clonedSvgElement = svgElement.cloneNode(true);
const outerHTML = clonedSvgElement.outerHTML,
blob = new Blob([outerHTML], { type: 'image/svg+xml;charset=utf-8' });
const URL = window.URL || window.webkitURL || window;
const blobURL = (URL as any).createObjectURL(blob);
let image = new Image();
image.onload = () => {
let canvas = this.canvas.nativeElement;
canvas.width = width;
canvas.height = height;
let context = canvas.getContext('2d');
// draw image in canvas starting left-0 , top - 0
context.drawImage(image, 0, 0, width, height); //
//downloadImage(canvas); //need to implement};
};
image.src = blobURL;
const ctx = this.canvas2.nativeElement.getContext('2d');
this.v = await Canvg.fromString(
ctx,
'<svg><path fill-rule="evenodd" d="M1 8a7 7 0 1 0 14 0A7 7 0 0 0 1 8zm15 0A8 8 0 1 1 0 8a8 8 0 0 1 16 0zm-4.5-.5a.5.5 0 0 1 0 1H5.707l2.147 2.146a.5.5 0 0 1-.708.708l-3-3a.5.5 0 0 1 0-.708l3-3a.5.5 0 1 1 .708.708L5.707 7.5H11.5z"/></svg>'
);
this.v.start();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.