UNPKG

nativescript-gif

Version:
122 lines 4.14 kB
import { knownFolders, PercentLength } from '@nativescript/core'; import { GifCommon, headersProperty, srcProperty } from './gif.common'; export class Gif extends GifCommon { constructor() { super(); this.nativeView = FLAnimatedImageView.alloc().initWithFrame(CGRectMake(0, 0, 100, 100)); this.nativeView.clipsToBounds = true; this._headers = null; this._src = null; } [headersProperty.setNative](value) { this._setHeader(value ? value : null); } [srcProperty.setNative](value) { this._setSrcProperty(value); } _setSrcProperty(value) { if (value) { let isUrl = false; if (value.indexOf('://') !== -1) { if (value.indexOf('res://') === -1) { isUrl = true; } } this._src = value; if (!isUrl) { const currentPath = knownFolders.currentApp().path; if (value[1] === '/' && (value[0] === '.' || value[0] === '~')) { value = value.substr(2); } if (value[0] !== '/') { value = currentPath + '/' + value; } this._animatedImage = FLAnimatedImage.animatedImageWithGIFData(NSData.dataWithContentsOfFile(NSString.stringWithString(value))); this._setImage(); } else { if (this._headers) { this._useAnimatedImageFromUrl(value, this._headers); } else { this._useAnimatedImageFromUrl(value); } } } else { console.log('No src value detected.'); } } stop() { this.nativeView.stopAnimating(); } start() { this.nativeView.startAnimating(); } reset() { let temp = this.nativeView.animatedImage; this.nativeView.animatedImage = null; this.nativeView.animatedImage = temp; temp = null; } isPlaying() { return this.nativeView.animating; } getFrameCount() { const frames = this.nativeView.animatedImage.frameCount; return frames; } _useAnimatedImageFromUrl(url, headers) { const nsUrl = NSURL.URLWithString(url); if (headers) { const request = NSMutableURLRequest.requestWithURL(nsUrl); for (const property in headers) { if (headers.hasOwnProperty(property)) { request.addValueForHTTPHeaderField(headers[property], property); } } request.HTTPMethod = 'GET'; const session = NSURLSession.sharedSession; const task = session.dataTaskWithRequestCompletionHandler(request, (data, response, err) => { if (err) { console.log('Error loading Gif: ' + err.localizedDescription); } else { this._animatedImage = FLAnimatedImage.animatedImageWithGIFData(data); this._setImage(); } }); task.resume(); } else { const data = NSData.dataWithContentsOfURL(nsUrl); this._animatedImage = FLAnimatedImage.animatedImageWithGIFData(data); this._setImage(); } } _setImage() { try { this.nativeView.animatedImage = this._animatedImage; this.nativeView.frame = CGRectMake(0, 0, 100, 100); } catch (ex) { console.log(ex); } if (isNaN(PercentLength.toDevicePixels(this.width)) || isNaN(PercentLength.toDevicePixels(this.height))) { this.requestLayout(); } } _setHeader(headers) { if (headers) { this._headers = headers; if (this._src && this._src.length > 0) { this._setSrcProperty(this._src); } } else { this._headers = null; } } } //# sourceMappingURL=gif.ios.js.map