@nativescript-community/ui-image
Version:
Advanced and efficient image display plugin which uses Glide (Android) and SDWebImage (iOS) to implement caching, placeholders, image effects, and much more.
907 lines • 36.7 kB
JavaScript
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
export * from './index-common';
import { ImageAsset, ImageSource, Trace, Utils, backgroundInternalProperty, knownFolders, path } from '@nativescript/core';
import { isString } from '@nativescript/core/utils/types';
import { CLog, CLogTypes, ImageBase, ScaleType, aspectRatioProperty, backgroundUriProperty, blurDownSamplingProperty, blurRadiusProperty, decodeHeightProperty, decodeWidthProperty, fadeDurationProperty, failureImageUriProperty, headersProperty, imageRotationProperty, lowerResSrcProperty, needRequestImage, noRatioEnforceProperty, placeholderImageUriProperty, roundAsCircleProperty, roundBottomLeftRadiusProperty, roundBottomRightRadiusProperty, roundTopLeftRadiusProperty, roundTopRightRadiusProperty, srcProperty, stretchProperty, tintColorProperty, wrapNativeException } from './index-common';
let initialized = false;
let glideInstance;
// global signature to invalidate all cache if needed by plugin
let signature;
const globalSignatureKey = 'v1';
export function initialize(config) {
if (!initialized) {
const context = Utils.android.getApplicationContext();
const glideConfig = com.nativescript.image.GlideConfiguration.getInstance();
if (config?.memoryCacheSize > 0) {
glideConfig.setMemoryCacheSize(config.memoryCacheSize);
}
if (config?.memoryCacheScreens > 0) {
glideConfig.setMemoryCacheScreens(config.memoryCacheScreens);
}
signature = new com.bumptech.glide.signature.ObjectKey(config?.globalSignatureKey || globalSignatureKey);
// Now initialize Glide (which will read from GlideConfiguration)
glideInstance = com.bumptech.glide.Glide.get(context);
// this is needed for further buildKey to trigger ...
com.bumptech.glide.Glide.with(context).load('toto').apply(new com.bumptech.glide.request.RequestOptions().signature(signature)).preload();
// com.nativescript.image.EngineKeyFactoryMethodDumper.dumpKeyFactoryMethods(glideInstance);
// com.nativescript.image.ForcePreloadTest.forcePreloadAfterInjection(context, 'https://example.com/test-image.png');
initialized = true;
}
}
export class ImagePipeline {
toUri(value) {
if (value instanceof android.net.Uri) {
return value.toString();
}
return value;
}
getCacheKey(uri, context) {
return uri;
}
isInDiskCache(uri) {
const url = this.toUri(uri);
return new Promise((resolve, reject) => {
com.nativescript.image.EvictionManager.get().isInDiskCacheAsync(url, new com.nativescript.image.EvictionManager.DiskPresenceCallback({
onResult(source, transform) {
resolve(source || transform);
}
}));
});
}
isInBitmapMemoryCache(uri) {
// Still not directly accessible, but we can check if it's registered
const url = this.toUri(uri);
return com.nativescript.image.EvictionManager.get().isInMemoryCache(url);
}
evictFromMemoryCache(uri) {
const url = this.toUri(uri);
return new Promise((resolve, reject) => {
com.nativescript.image.EvictionManager.get().evictMemoryForId(url, new com.nativescript.image.EvictionManager.EvictionCallback({
onComplete(success, error) {
if (success) {
resolve();
}
else {
if (Trace.isEnabled()) {
CLog(CLogTypes.error, error);
}
reject(error);
}
}
}));
});
}
evictFromDiskCache(uri) {
const url = this.toUri(uri);
return new Promise((resolve, reject) => {
com.nativescript.image.EvictionManager.get().evictDiskForId(url, new com.nativescript.image.EvictionManager.EvictionCallback({
onComplete(success, error) {
if (success) {
resolve();
}
else {
if (Trace.isEnabled()) {
CLog(CLogTypes.error, error);
}
reject(error);
}
}
}));
});
}
evictFromCache(uri) {
const url = this.toUri(uri);
return new Promise((resolve, reject) => {
com.nativescript.image.EvictionManager.get().evictAllForId(url, new com.nativescript.image.EvictionManager.EvictionCallback({
onComplete(success, error) {
if (success) {
resolve();
}
else {
if (Trace.isEnabled()) {
CLog(CLogTypes.error, error);
}
reject(error);
}
}
}));
});
}
clearCaches() {
return new Promise((resolve, reject) => {
com.nativescript.image.EvictionManager.get().clearAll(new com.nativescript.image.EvictionManager.EvictionCallback({
onComplete(success, error) {
if (success) {
resolve();
}
else {
if (Trace.isEnabled()) {
CLog(CLogTypes.error, error);
}
reject(error);
}
}
}));
});
}
clearMemoryCaches() {
return new Promise((resolve, reject) => {
com.nativescript.image.EvictionManager.get().clearMemory(new com.nativescript.image.EvictionManager.EvictionCallback({
onComplete(success, error) {
if (success) {
resolve();
}
else {
if (Trace.isEnabled()) {
CLog(CLogTypes.error, error);
}
reject(error);
}
}
}));
});
}
clearDiskCaches() {
return new Promise((resolve, reject) => {
com.nativescript.image.EvictionManager.get().clearDiskCache(new com.nativescript.image.EvictionManager.EvictionCallback({
onComplete(success, error) {
if (success) {
resolve();
}
else {
if (Trace.isEnabled()) {
CLog(CLogTypes.error, error);
}
reject(error);
}
}
}));
});
}
prefetchToDiskCache(uri) {
return this.prefetchToCache(uri, true);
}
prefetchToMemoryCache(uri) {
return new Promise((resolve, reject) => {
try {
const context = Utils.android.getApplicationContext();
const requestManager = com.bumptech.glide.Glide.with(context);
const requestBuilder = requestManager.asBitmap().load(uri).apply(new com.bumptech.glide.request.RequestOptions().signature(signature));
let futureTarget = null;
function clearLater() {
if (futureTarget) {
setTimeout(() => {
com.bumptech.glide.Glide.with(context).clear(futureTarget);
}, 0);
}
}
const listener = new com.bumptech.glide.request.RequestListener({
onLoadFailed(e, model, target, isFirstResource) {
clearLater();
reject(e);
return true; // consumed
},
onResourceReady(resource, model, target, dataSource, isFirstResource) {
clearLater();
resolve();
return true; // consumed
}
});
// Kick the request off and keep a reference to the FutureTarget so it can be cleared.
futureTarget = requestBuilder.listener(listener).preload();
}
catch (error) {
reject(error);
}
});
}
prefetchToCache(uri, toDiskCache) {
return new Promise((resolve, reject) => {
try {
const context = Utils.android.getApplicationContext();
const requestManager = com.bumptech.glide.Glide.with(context);
const requestBuilder = (toDiskCache ? requestManager.downloadOnly().load(uri) : requestManager.asBitmap().load(uri)).apply(new com.bumptech.glide.request.RequestOptions().signature(signature));
let futureTarget = null;
function clearLater() {
if (futureTarget) {
setTimeout(() => {
try {
com.bumptech.glide.Glide.with(context).clear(futureTarget);
}
catch (err) {
// ignore
}
}, 0);
}
}
const listener = new com.bumptech.glide.request.RequestListener({
onLoadFailed(e, model, target, isFirstResource) {
clearLater();
reject(e);
return true;
},
onResourceReady(resource, model, target, dataSource, isFirstResource) {
clearLater();
resolve();
return true;
}
});
futureTarget = requestBuilder.listener(listener).preload();
}
catch (error) {
reject(error);
}
});
}
get android() {
return glideInstance;
}
}
let imagePipeLine;
export function getImagePipeline() {
if (!imagePipeLine) {
imagePipeLine = new ImagePipeline();
}
return imagePipeLine;
}
export function shutDown() {
if (!initialized) {
return;
}
initialized = false;
// Glide cleanup
const context = Utils.android.getApplicationContext();
if (context) {
com.bumptech.glide.Glide.get(context).clearMemory();
}
}
function getUri(src, asNative = true) {
let uri;
let imagePath;
if (src instanceof ImageAsset) {
imagePath = src.android;
}
else {
imagePath = src;
}
if (Utils.isFileOrResourcePath(imagePath)) {
if (imagePath.indexOf(Utils.RESOURCE_PREFIX) === 0) {
const resName = imagePath.substring(Utils.RESOURCE_PREFIX.length);
const identifier = Utils.android.resources.getDrawableId(resName);
if (0 < identifier) {
return `android.resource://${Utils.android.getApplicationContext().getPackageName()}/${identifier}`;
}
}
else if (imagePath.indexOf('~/') === 0) {
uri = `file://${path.join(knownFolders.currentApp().path, imagePath.replace('~/', ''))}`;
}
else if (imagePath.indexOf('/') === 0) {
uri = `file://${imagePath}`;
}
}
else {
uri = imagePath;
}
return uri;
}
export class ImageError {
constructor(throwable) {
this._message = throwable.getMessage();
this._errorType = throwable.getClass().getName();
this._stringValue = throwable.toString();
}
getMessage() {
return this._message;
}
getErrorType() {
return this._errorType;
}
toString() {
return this._stringValue;
}
}
export class ImageInfo {
constructor(width, height) {
this._width = width;
this._height = height;
}
getHeight() {
return this._height;
}
getWidth() {
return this._width;
}
getQualityInfo() {
return {
getQuality: () => 1,
isOfFullQuality: () => true,
isOfGoodEnoughQuality: () => true
};
}
}
export class Img extends ImageBase {
constructor() {
super(...arguments);
this.preventPreClearDrawable = false;
this.mNeedUpdateLayout = false;
this.currentTarget = null;
this.isNetworkRequest = false;
this.progressCallback = null;
this.loadSourceCallback = null;
}
createNativeView() {
if (!initialized) {
initialize();
}
return new com.nativescript.image.MatrixImageView(this._context);
}
disposeNativeView() {
// Cancel any running Glide requests before dispose
this.cancelCurrentRequest();
this.progressCallback = null;
this.loadSourceCallback = null;
}
get cacheKey() {
const src = this.src;
const srcType = typeof src;
if (src && (srcType === 'string' || src instanceof ImageAsset)) {
return getUri(src);
}
return undefined;
}
async updateImageUri() {
const imagePipeLine = getImagePipeline();
const cacheKey = this.cacheKey;
if (cacheKey) {
await imagePipeLine.evictFromCache(cacheKey);
}
this.handleImageSrc(null);
this.initImage();
}
[_a = placeholderImageUriProperty.setNative]() { }
[_b = failureImageUriProperty.setNative]() { }
[stretchProperty.setNative]() {
// Scale type
if (this.stretch) {
const scaleType = getScaleType(this.stretch);
if (scaleType) {
this.nativeViewProtected.setScaleType(scaleType);
}
}
}
[_c = fadeDurationProperty.setNative]() { }
[_d = backgroundUriProperty.setNative]() { }
[_e = roundAsCircleProperty.setNative](value) { }
[_f = roundTopLeftRadiusProperty.setNative]() { }
[imageRotationProperty.setNative](value) {
this.nativeImageViewProtected?.setImageRotation(value);
}
[_g = roundTopRightRadiusProperty.setNative]() { }
[_h = roundBottomLeftRadiusProperty.setNative]() { }
[_j = roundBottomRightRadiusProperty.setNative]() { }
[tintColorProperty.setNative](value) {
if (this.nativeImageViewProtected) {
this.nativeImageViewProtected.setColorFilter(value?.android ?? -1, android.graphics.PorterDuff.Mode.MULTIPLY);
}
}
[_k = blurRadiusProperty.setNative](value) { }
[_l = srcProperty.setNative]() { }
[_m = decodeWidthProperty.setNative]() { }
[_o = decodeHeightProperty.setNative]() { }
[_p = lowerResSrcProperty.setNative]() { }
[_q = blurDownSamplingProperty.setNative]() { }
[aspectRatioProperty.setNative](value) {
if (this.nativeViewProtected) {
this.nativeViewProtected.setAspectRatio(value || 0);
}
}
[_r = headersProperty.setNative](value) { }
[backgroundInternalProperty.setNative](value) {
super[backgroundInternalProperty.setNative](value);
if (this.nativeViewProtected) {
this.nativeViewProtected.setClipToOutline(value?.hasBorderRadius());
}
}
[noRatioEnforceProperty.setNative](value) {
if (this.nativeViewProtected) {
this.nativeViewProtected.setNoRatioEnforce(value);
}
}
// Clear any active Glide target/request attached to this view.
cancelCurrentRequest() {
const ctx = this._context;
if (!ctx) {
return;
}
if (this.currentTarget) {
// cancel and drop reference; Any callbacks from the old target will be swallowed.
try {
com.bumptech.glide.Glide.with(ctx).clear(this.currentTarget);
}
catch (err) {
// ignore
}
this.currentTarget = null;
}
// if (this.nativeViewProtected) {
// try {
// com.bumptech.glide.Glide.with(ctx).clear(this.nativeViewProtected);
// } catch (err) {
// // ignore
// }
// }
}
loadImageWithGlide(uri) {
const view = this.nativeViewProtected;
const context = this._context;
// Cancel any prior Glide request/target for this view before starting a new one.
this.cancelCurrentRequest();
// Determine if this is a network request
this.isNetworkRequest = typeof uri === 'string' && (uri.startsWith('http://') || uri.startsWith('https://'));
let requestBuilder;
let loadModel = uri;
// Create callbacks separately based on what's needed
const needsProgress = this.isNetworkRequest && this.hasListeners(ImageBase.progressEvent);
const needsLoadSource = this.isNetworkRequest && this.hasListeners('loadSource');
// Create progress callback if needed (only for network requests with listener)
if (needsProgress) {
const owner = new WeakRef(this);
this.progressCallback = new com.nativescript.image.ImageProgressCallback({
onProgress(url, bytesRead, totalBytes) {
const instance = owner.get();
if (instance) {
const progress = totalBytes > 0 ? bytesRead / totalBytes : 0;
instance.notifyProgress({
loaded: bytesRead,
total: totalBytes,
progress,
finished: bytesRead >= totalBytes
});
}
}
});
}
// Create load source callback if needed (separate from progress)
if (needsLoadSource) {
const owner = new WeakRef(this);
this.loadSourceCallback = new com.nativescript.image.ImageLoadSourceCallback({
onLoadStarted(url, source) {
const instance = owner.get();
if (instance) {
instance.notifyLoadSource(source);
}
}
});
}
// Use CustomGlideUrl if we need headers, progress, or load source
if (this.isNetworkRequest && (this.headers || this.progressCallback || this.loadSourceCallback)) {
const headersMap = new java.util.HashMap();
if (this.headers) {
for (const key in this.headers) {
headersMap.put(key, this.headers[key]);
}
}
loadModel = new com.nativescript.image.CustomGlideUrl(uri, headersMap, this.progressCallback, // Can be null
this.loadSourceCallback // Can be null
);
}
requestBuilder = com.bumptech.glide.Glide.with(context).load(loadModel);
// Apply transformations (blur, rounded corners, etc.)
const transformations = [];
if (this.blurRadius) {
transformations.push(new jp.wasabeef.glide.transformations.BlurTransformation(Math.round(this.blurRadius), this.blurDownSampling || 1));
}
if (this.roundAsCircle) {
transformations.push(new jp.wasabeef.glide.transformations.CropCircleTransformation());
}
else {
const topLeft = Utils.layout.toDevicePixels(this.roundTopLeftRadius || 0);
const topRight = Utils.layout.toDevicePixels(this.roundTopRightRadius || 0);
const bottomRight = Utils.layout.toDevicePixels(this.roundBottomRightRadius || 0);
const bottomLeft = Utils.layout.toDevicePixels(this.roundBottomLeftRadius || 0);
if (topLeft || topRight || bottomRight || bottomLeft) {
const radius = Math.max(topLeft, topRight, bottomRight, bottomLeft);
transformations.push(new jp.wasabeef.glide.transformations.RoundedCornersTransformation(Math.round(radius), 0, jp.wasabeef.glide.transformations.RoundedCornersTransformation.CornerType.ALL));
}
}
// Tint color
if (this.tintColor) {
transformations.push(new jp.wasabeef.glide.transformations.ColorFilterTransformation(this.tintColor.android));
}
let multiTransform;
if (transformations.length > 0) {
multiTransform = new com.bumptech.glide.load.MultiTransformation(java.util.Arrays.asList(transformations));
requestBuilder = requestBuilder.transform(multiTransform);
}
// Placeholder
if (this.placeholderImageUri) {
const placeholder = this.getDrawable(this.placeholderImageUri);
if (placeholder) {
requestBuilder = requestBuilder.placeholder(placeholder);
}
}
// Error image
if (this.failureImageUri) {
const error = this.getDrawable(this.failureImageUri);
if (error) {
requestBuilder = requestBuilder.error(error);
}
}
// Thumbnail
if (this.lowerResSrc) {
const lowerResUri = getUri(this.lowerResSrc);
if (lowerResUri) {
const thumbnailRequest = com.bumptech.glide.Glide.with(context).load(lowerResUri);
requestBuilder = requestBuilder.thumbnail(thumbnailRequest);
}
}
// Fade duration + conditional crossfade
if (this.fadeDuration > 0) {
const factory = new com.nativescript.image.ConditionalCrossFadeFactory(this.fadeDuration, !this.alwaysFade);
requestBuilder = requestBuilder.transition(com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade(factory));
}
// Cache settings
if (this.noCache) {
requestBuilder = requestBuilder.skipMemoryCache(true).diskCacheStrategy(com.bumptech.glide.load.engine.DiskCacheStrategy.NONE);
}
// Decode size
if (this.decodeWidth || this.decodeHeight) {
const Target = com.bumptech.glide.request.target.Target;
const width = this.decodeWidth || Target.SIZE_ORIGINAL;
const height = this.decodeHeight || Target.SIZE_ORIGINAL;
if (width === Target.SIZE_ORIGINAL) {
requestBuilder = requestBuilder.override(height);
}
else if (height === Target.SIZE_ORIGINAL) {
requestBuilder = requestBuilder.override(width);
}
else {
requestBuilder = requestBuilder.override(width, height);
}
}
const owner = new WeakRef(this);
const sourceKey = new com.bumptech.glide.signature.ObjectKey(uri);
const objectArr = Array.create(com.bumptech.glide.request.RequestListener, 2);
const ro = new com.bumptech.glide.request.RequestOptions().signature(signature);
objectArr[0] = new com.nativescript.image.SaveKeysRequestListener(uri, uri, sourceKey, signature, this.decodeWidth || com.bumptech.glide.request.target.Target.SIZE_ORIGINAL, this.decodeHeight || com.bumptech.glide.request.target.Target.SIZE_ORIGINAL, multiTransform, ro, null);
objectArr[1] = new com.bumptech.glide.request.RequestListener({
onLoadFailed(e, model, target, isFirstResource) {
const instance = owner.get();
if (instance) {
// If this callback is for a previously canceled request, swallow it to avoid
// emitting/logging errors for obsolete requests.
if (instance.currentTarget && target !== instance.currentTarget) {
instance.progressCallback = null;
instance.loadSourceCallback = null;
// Swallow: we handled it (don't let Glide default log/clear)
return true;
}
instance.currentTarget = null;
instance.progressCallback = null; // Clean up
instance.loadSourceCallback = null;
instance.notifyFailure(e);
}
return false;
},
onResourceReady(resource, model, target, dataSource, isFirstResource) {
const instance = owner.get();
if (instance) {
// Ignore if the callback is from a previous request (stale).
if (instance.currentTarget && target !== instance.currentTarget) {
instance.progressCallback = null;
instance.loadSourceCallback = null;
return true;
}
instance.currentTarget = null;
instance.progressCallback = null; // Clean up
instance.loadSourceCallback = null;
instance.notifyFinalImageSet(resource, dataSource);
// Handle auto-play for animated drawables
if (!instance.autoPlayAnimations && resource instanceof android.graphics.drawable.Animatable) {
setTimeout(() => {
resource.stop();
}, 0);
}
// Notify load source for cache hits (network notified by interceptor)
let source = 'local';
if (dataSource) {
try {
const sourceName = dataSource.name ? dataSource.name() : String(dataSource);
switch ((sourceName || '').toUpperCase()) {
case 'MEMORY_CACHE':
source = 'memory';
break;
case 'DATA_DISK_CACHE':
case 'RESOURCE_DISK_CACHE':
source = 'disk';
break;
case 'REMOTE':
source = 'network';
break;
case 'LOCAL':
source = 'local';
break;
}
}
catch (err) {
source = 'unknown';
}
}
// Only notify if not network (network already notified by interceptor)
if (source !== 'network' && instance.hasListeners('loadSource')) {
instance.notifyLoadSource(source);
}
}
return false;
}
});
// Always create and track our custom target so we can detect stale callbacks later.
const target = new com.nativescript.image.MatrixDrawableImageViewTarget(view);
this.currentTarget = target;
if (this.preventPreClearDrawable) {
target.setClearFirst(false);
}
requestBuilder.apply(ro).listener(new com.nativescript.image.CompositeRequestListener(objectArr)).into(target);
}
notifyLoadSource(source) {
const eventName = ImageBase.loadSourceEvent;
if (this.hasListeners(eventName)) {
this.notify({
eventName,
source // 'network', 'memory', 'disk', 'local'
});
}
}
notifyProgress(payload) {
const eventName = ImageBase.progressEvent;
if (this.hasListeners(eventName)) {
this.notify({
eventName,
current: payload.loaded,
total: payload.total,
progress: payload.progress,
finished: payload.finished
});
}
}
notifyFinalImageSet(drawable, dataSource) {
let sourceLabel = 'local';
if (dataSource) {
try {
sourceLabel = dataSource.name ? dataSource.name() : String(dataSource);
}
catch (err) {
sourceLabel = String(dataSource);
}
switch ((sourceLabel || '').toUpperCase()) {
case 'MEMORY_CACHE':
sourceLabel = 'memory';
break;
case 'DATA_DISK_CACHE':
case 'RESOURCE_DISK_CACHE':
sourceLabel = 'disk';
break;
case 'REMOTE':
sourceLabel = 'network';
break;
case 'LOCAL':
sourceLabel = 'local';
break;
default:
break;
}
}
const eventName = ImageBase.finalImageSetEvent;
if (this.hasListeners(eventName)) {
const width = drawable ? drawable.getIntrinsicWidth() : 0;
const height = drawable ? drawable.getIntrinsicHeight() : 0;
const info = new ImageInfo(width, height);
this.notify({
eventName,
imageInfo: info,
animatable: this.getAnimatable(drawable),
android: drawable,
source: sourceLabel
});
}
}
notifyFailure(error) {
const eventName = ImageBase.failureEvent;
if (this.hasListeners(eventName)) {
this.notify({
eventName,
error: error instanceof java.lang.Throwable ? wrapNativeException(error) : error
});
}
}
getAnimatable(drawable) {
if (drawable && drawable instanceof android.graphics.drawable.Animatable) {
return drawable;
}
return null;
}
async handleImageSrc(src) {
const view = this.nativeViewProtected;
if (!view) {
return;
}
if (src instanceof Promise) {
this.handleImageSrc(await src);
return;
}
else if (typeof src === 'function') {
const newSrc = src();
if (newSrc instanceof Promise) {
await newSrc;
}
this.handleImageSrc(newSrc);
return;
}
if (src) {
let drawable;
if (typeof src === 'string') {
if (Utils.isFontIconURI(src)) {
const fontIconCode = src.split('//')[1];
if (fontIconCode !== undefined) {
const font = this.style.fontInternal;
const color = this.style.color;
drawable = new android.graphics.drawable.BitmapDrawable(Utils.android.getApplicationContext().getResources(), ImageSource.fromFontIconCodeSync(fontIconCode, font, color).android);
}
}
}
else if (src instanceof ImageSource) {
drawable = new android.graphics.drawable.BitmapDrawable(Utils.android.getApplicationContext().getResources(), src.android);
}
if (drawable) {
view.setImageDrawable(drawable);
this.notifyFinalImageSet(drawable);
return;
}
const uri = getUri(src);
if (!uri) {
console.error(`Error: 'src' not valid: ${src}`);
return;
}
this.loadImageWithGlide(uri);
}
else {
// Clear existing request before removing the drawable
this.cancelCurrentRequest();
view.setImageDrawable(null);
}
}
async initImage() {
try {
await this.handleImageSrc(this.src);
}
catch (error) {
console.error(error, error.stack);
}
}
getDrawable(path) {
if (typeof path === 'string') {
if (Utils.isFontIconURI(path)) {
const fontIconCode = path.split('//')[1];
if (fontIconCode !== undefined) {
const font = this.style.fontInternal;
const color = this.style.color;
return new android.graphics.drawable.BitmapDrawable(Utils.android.getApplicationContext().getResources(), ImageSource.fromFontIconCodeSync(fontIconCode, font, color).android);
}
}
else if (Utils.isFileOrResourcePath(path)) {
if (path.indexOf(Utils.RESOURCE_PREFIX) === 0) {
return this.getDrawableFromResource(path);
}
else {
return this.getDrawableFromLocalFile(path);
}
}
}
else if (path instanceof ImageSource) {
return new android.graphics.drawable.BitmapDrawable(Utils.android.getApplicationContext().getResources(), path.android);
}
return null;
}
getDrawableFromLocalFile(localFilePath) {
const img = ImageSource.fromFileSync(localFilePath);
if (img) {
return new android.graphics.drawable.BitmapDrawable(Utils.android.getApplicationContext().getResources(), img.android);
}
return null;
}
getDrawableFromResource(resourceName) {
const application = Utils.android.getApplication();
const resources = application.getResources();
const identifier = resources.getIdentifier(resourceName.substring(Utils.RESOURCE_PREFIX.length), 'drawable', application.getPackageName());
return identifier;
}
startAnimating() {
const drawable = this.nativeViewProtected.getDrawable();
if (drawable && drawable instanceof android.graphics.drawable.Animatable) {
drawable.start();
}
}
stopAnimating() {
const drawable = this.nativeViewProtected.getDrawable();
if (drawable && drawable instanceof android.graphics.drawable.Animatable) {
drawable.stop();
}
}
}
__decorate([
needRequestImage
], Img.prototype, _a, null);
__decorate([
needRequestImage
], Img.prototype, _b, null);
__decorate([
needRequestImage
], Img.prototype, _c, null);
__decorate([
needRequestImage
], Img.prototype, _d, null);
__decorate([
needRequestImage
], Img.prototype, _e, null);
__decorate([
needRequestImage
], Img.prototype, _f, null);
__decorate([
needRequestImage
], Img.prototype, _g, null);
__decorate([
needRequestImage
], Img.prototype, _h, null);
__decorate([
needRequestImage
], Img.prototype, _j, null);
__decorate([
needRequestImage
], Img.prototype, _k, null);
__decorate([
needRequestImage
], Img.prototype, _l, null);
__decorate([
needRequestImage
], Img.prototype, _m, null);
__decorate([
needRequestImage
], Img.prototype, _o, null);
__decorate([
needRequestImage
], Img.prototype, _p, null);
__decorate([
needRequestImage
], Img.prototype, _q, null);
__decorate([
needRequestImage
], Img.prototype, _r, null);
function getScaleType(scaleType) {
if (isString(scaleType)) {
switch (scaleType) {
case ScaleType.Center:
return android.widget.ImageView.ScaleType.CENTER;
case ScaleType.AspectFill:
case ScaleType.CenterCrop:
return android.widget.ImageView.ScaleType.CENTER_CROP;
case ScaleType.CenterInside:
return android.widget.ImageView.ScaleType.CENTER_INSIDE;
case ScaleType.FitCenter:
case ScaleType.AspectFit:
return android.widget.ImageView.ScaleType.FIT_CENTER;
case ScaleType.FitEnd:
return android.widget.ImageView.ScaleType.FIT_END;
case ScaleType.FitStart:
return android.widget.ImageView.ScaleType.FIT_START;
case ScaleType.Fill:
case ScaleType.FitXY:
return android.widget.ImageView.ScaleType.FIT_XY;
case ScaleType.FocusCrop:
return android.widget.ImageView.ScaleType.CENTER_CROP;
default:
return android.widget.ImageView.ScaleType.FIT_CENTER;
}
}
return android.widget.ImageView.ScaleType.FIT_CENTER;
}
//# sourceMappingURL=index.android.js.map