类com.bumptech.glide.util.Util源码实例Demo

下面列出了怎么用com.bumptech.glide.util.Util的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: giffun   文件: GenericRequest.java
/**
 * {@inheritDoc}
 */
@Override
public void begin() {
    startTime = LogTime.getLogTime();
    if (model == null) {
        onException(null);
        return;
    }

    status = Status.WAITING_FOR_SIZE;
    if (Util.isValidDimensions(overrideWidth, overrideHeight)) {
        onSizeReady(overrideWidth, overrideHeight);
    } else {
        target.getSize(this);
    }

    if (!isComplete() && !isFailed() && canNotifyStatusChanged()) {
        target.onLoadStarted(getPlaceholderDrawable());
    }
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        logV("finished run method in " + LogTime.getElapsedMillis(startTime));
    }
}
 
源代码2 项目: giffun   文件: GenericRequest.java
/**
 * Cancels the current load if it is in progress, clears any resources held onto by the request and replaces
 * the loaded resource if the load completed with the placeholder.
 *
 * <p>
 *     Cleared requests can be restarted with a subsequent call to {@link #begin()}
 * </p>
 *
 * @see #cancel()
 */
@Override
public void clear() {
    Util.assertMainThread();
    if (status == Status.CLEARED) {
        return;
    }
    cancel();
    // Resource must be released before canNotifyStatusChanged is called.
    if (resource != null) {
        releaseResource(resource);
    }
    if (canNotifyStatusChanged()) {
        target.onLoadCleared(getPlaceholderDrawable());
    }
    // Must be after cancel().
    status = Status.CLEARED;
}
 
源代码3 项目: giffun   文件: GenericRequestBuilder.java
/**
 * Set the target the resource will be loaded into.
 *
 * @see Glide#clear(Target)
 *
 * @param target The target to load the resource into.
 * @return The given target.
 */
public <Y extends Target<TranscodeType>> Y into(Y target) {
    Util.assertMainThread();
    if (target == null) {
        throw new IllegalArgumentException("You must pass in a non null Target");
    }
    if (!isModelSet) {
        throw new IllegalArgumentException("You must first set a model (try #load())");
    }

    Request previous = target.getRequest();

    if (previous != null) {
        previous.clear();
        requestTracker.removeRequest(previous);
        previous.recycle();
    }

    Request request = buildRequest(target);
    target.setRequest(request);
    lifecycle.addListener(target);
    requestTracker.runRequest(request);

    return target;
}
 
源代码4 项目: giffun   文件: GenericRequestBuilder.java
/**
 * Sets the {@link ImageView} the resource will be loaded into, cancels any existing loads into the view, and frees
 * any resources Glide may have previously loaded into the view so they may be reused.
 *
 * @see Glide#clear(android.view.View)
 *
 * @param view The view to cancel previous loads for and load the new resource into.
 * @return The {@link Target} used to wrap the given {@link ImageView}.
 */
public Target<TranscodeType> into(ImageView view) {
    Util.assertMainThread();
    if (view == null) {
        throw new IllegalArgumentException("You must pass in a non null View");
    }

    if (!isTransformationSet && view.getScaleType() != null) {
        switch (view.getScaleType()) {
            case CENTER_CROP:
                applyCenterCrop();
                break;
            case FIT_CENTER:
            case FIT_START:
            case FIT_END:
                applyFitCenter();
                break;
            //$CASES-OMITTED$
            default:
                // Do nothing.
        }
    }

    return into(glide.buildImageViewTarget(view, transcodeClass));
}
 
源代码5 项目: giffun   文件: BitmapTransformation.java
@Override
public final Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth, int outHeight) {
    if (!Util.isValidDimensions(outWidth, outHeight)) {
        throw new IllegalArgumentException("Cannot apply transformation on width: " + outWidth + " or height: "
                + outHeight + " less than or equal to zero and not Target.SIZE_ORIGINAL");
    }
    Bitmap toTransform = resource.get();
    int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
    int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
    Bitmap transformed = transform(bitmapPool, toTransform, targetWidth, targetHeight);

    final Resource<Bitmap> result;
    if (toTransform.equals(transformed)) {
        result = resource;
    } else {
        result = BitmapResource.obtain(transformed, bitmapPool);
    }

    return result;
}
 
源代码6 项目: giffun   文件: BitmapPreFillRunner.java
/**
 * Attempts to allocate {@link Bitmap}s and returns {@code true} if there are more
 * {@link Bitmap}s to allocate and {@code false} otherwise.
 */
private boolean allocate() {
    long start = clock.now();
    while (!toPrefill.isEmpty() && !isGcDetected(start)) {
        PreFillType toAllocate = toPrefill.remove();
        Bitmap bitmap = Bitmap.createBitmap(toAllocate.getWidth(), toAllocate.getHeight(),
                toAllocate.getConfig());

        // Don't over fill the memory cache to avoid evicting useful resources, but make sure it's not empty so
        // we use all available space.
        if (getFreeMemoryCacheBytes() >= Util.getBitmapByteSize(bitmap)) {
            memoryCache.put(new UniqueKey(), BitmapResource.obtain(bitmap, bitmapPool));
        } else {
            addToBitmapPool(toAllocate, bitmap);
        }

        if (Log.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "allocated [" + toAllocate.getWidth() + "x" + toAllocate.getHeight() + "] "
                    + toAllocate.getConfig() + " size: " + Util.getBitmapByteSize(bitmap));
        }
    }

    return !isCancelled && !toPrefill.isEmpty();
}
 
源代码7 项目: giffun   文件: SizeStrategy.java
@Override
public Bitmap get(int width, int height, Bitmap.Config config) {
    final int size = Util.getBitmapByteSize(width, height, config);
    Key key = keyPool.get(size);

    Integer possibleSize = sortedSizes.ceilingKey(size);
    if (possibleSize != null && possibleSize != size && possibleSize <= size * MAX_SIZE_MULTIPLE) {
        keyPool.offer(key);
        key = keyPool.get(possibleSize);
    }

    // Do a get even if we know we don't have a bitmap so that the key moves to the front in the lru pool
    final Bitmap result = groupedMap.get(key);
    if (result != null) {
        result.reconfigure(width, height, config);
        decrementBitmapOfSize(possibleSize);
    }

    return result;
}
 
源代码8 项目: AcgClub   文件: BitmapTransformation.java
@Override
public final Resource<Bitmap> transform(Context context, Resource<Bitmap> resource, int outWidth,
    int outHeight) {
  if (!Util.isValidDimensions(outWidth, outHeight)) {
    throw new IllegalArgumentException(
        "Cannot apply transformation on width: " + outWidth + " or height: " + outHeight
            + " less than or equal to zero and not Target.SIZE_ORIGINAL");
  }
  BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
  Bitmap toTransform = resource.get();
  int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
  int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
  Bitmap transformed = transform(context.getApplicationContext(), bitmapPool, toTransform,
      targetWidth, targetHeight);

  final Resource<Bitmap> result;
  if (toTransform.equals(transformed)) {
    result = resource;
  } else {
    result = BitmapResource.obtain(transformed, bitmapPool);
  }
  return result;
}
 
源代码9 项目: ImageLoader   文件: Glide4Loader.java
public String getSafeKey(Key key) {
    String safeKey;
    synchronized (loadIdToSafeHash) {
        safeKey = loadIdToSafeHash.get(key);
    }
    if (safeKey == null) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            key.updateDiskCacheKey(messageDigest);
            safeKey = Util.sha256BytesToHex(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        synchronized (loadIdToSafeHash) {
            loadIdToSafeHash.put(key, safeKey);
        }
    }
    return safeKey;
}
 
@NonNull
@Override
public final Resource<Bitmap> transform(@NonNull Context context, @NonNull Resource<Bitmap> resource,
                                        int outWidth, int outHeight) {
    if (!Util.isValidDimensions(outWidth, outHeight)) {
        throw new IllegalArgumentException(
                "Cannot apply transformation on width: " + outWidth + " or height: " + outHeight
                        + " less than or equal to zero and not Target.SIZE_ORIGINAL");
    }
    BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
    Bitmap toTransform = resource.get();
    System.out.println("target " + Target.SIZE_ORIGINAL + " outWidth " + outWidth  + " transform " +toTransform.getWidth()  );
    int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
    int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
    Bitmap transformed = transform(context.getApplicationContext(), bitmapPool, toTransform, targetWidth, targetHeight);

    final Resource<Bitmap> result;
    if (toTransform.equals(transformed)) {
        result = resource;
    } else {
        result = BitmapResource.obtain(transformed, bitmapPool);
    }
    return result;
}
 
@NonNull
@Override
public final Resource<Bitmap> transform(@NonNull Context context, @NonNull Resource<Bitmap> resource,
                                        int outWidth, int outHeight) {
  if (!Util.isValidDimensions(outWidth, outHeight)) {
    throw new IllegalArgumentException(
        "Cannot apply transformation on width: " + outWidth + " or height: " + outHeight
            + " less than or equal to zero and not Target.SIZE_ORIGINAL");
  }
  BitmapPool bitmapPool = Glide.get(context).getBitmapPool();
  Bitmap toTransform = resource.get();
  int targetWidth = outWidth == Target.SIZE_ORIGINAL ? toTransform.getWidth() : outWidth;
  int targetHeight = outHeight == Target.SIZE_ORIGINAL ? toTransform.getHeight() : outHeight;
  Bitmap transformed = transform(context.getApplicationContext(), bitmapPool, toTransform, targetWidth, targetHeight);

  final Resource<Bitmap> result;
  if (toTransform.equals(transformed)) {
    result = resource;
  } else {
    result = BitmapResource.obtain(transformed, bitmapPool);
  }
  return result;
}
 
源代码12 项目: giffun   文件: RequestFutureTarget.java
private synchronized R doGet(Long timeoutMillis) throws ExecutionException, InterruptedException, TimeoutException {
    if (assertBackgroundThread) {
        Util.assertBackgroundThread();
    }

    if (isCancelled) {
        throw new CancellationException();
    } else if (exceptionReceived) {
        throw new ExecutionException(exception);
    } else if (resultReceived) {
        return resource;
    }

    if (timeoutMillis == null) {
        waiter.waitForTimeout(this, 0);
    } else if (timeoutMillis > 0) {
        waiter.waitForTimeout(this, timeoutMillis);
    }

    if (Thread.interrupted()) {
        throw new InterruptedException();
    } else if (exceptionReceived) {
        throw new ExecutionException(exception);
    } else if (isCancelled) {
        throw new CancellationException();
    } else if (!resultReceived) {
        throw new TimeoutException();
    }

    return resource;
}
 
源代码13 项目: giffun   文件: SimpleTarget.java
/**
 * Immediately calls the given callback with the sizes given in the constructor.
 *
 * @param cb {@inheritDoc}
 */
@Override
public final void getSize(SizeReadyCallback cb) {
    if (!Util.isValidDimensions(width, height)) {
        throw new IllegalArgumentException("Width and height must both be > 0 or Target#SIZE_ORIGINAL, but given"
                + " width: " + width + " and height: " + height + ", either provide dimensions in the constructor"
                + " or call override()");
    }
    cb.onSizeReady(width, height);
}
 
源代码14 项目: giffun   文件: RequestTracker.java
/**
 * Stops any in progress requests.
 */
public void pauseRequests() {
    isPaused = true;
    for (Request request : Util.getSnapshot(requests)) {
        if (request.isRunning()) {
            request.pause();
            pendingRequests.add(request);
        }
    }
}
 
源代码15 项目: giffun   文件: RequestTracker.java
/**
 * Starts any not yet completed or failed requests.
 */
public void resumeRequests() {
    isPaused = false;
    for (Request request : Util.getSnapshot(requests)) {
        if (!request.isComplete() && !request.isCancelled() && !request.isRunning()) {
            request.begin();
        }
    }
    pendingRequests.clear();
}
 
源代码16 项目: giffun   文件: RequestTracker.java
/**
 * Cancels all requests and clears their resources.
 */
public void clearRequests() {
    for (Request request : Util.getSnapshot(requests)) {
        request.clear();
    }
    pendingRequests.clear();
}
 
源代码17 项目: giffun   文件: RequestTracker.java
/**
 * Restarts failed requests and cancels and restarts in progress requests.
 */
public void restartRequests() {
    for (Request request : Util.getSnapshot(requests)) {
        if (!request.isComplete() && !request.isCancelled()) {
            // Ensure the request will be restarted in onResume.
            request.pause();
            if (!isPaused) {
                request.begin();
            } else {
                pendingRequests.add(request);
            }
        }
    }
}
 
源代码18 项目: giffun   文件: RequestManagerRetriever.java
public RequestManager get(Context context) {
    if (context == null) {
        throw new IllegalArgumentException("You cannot start a load on a null Context");
    } else if (Util.isOnMainThread() && !(context instanceof Application)) {
        if (context instanceof FragmentActivity) {
            return get((FragmentActivity) context);
        } else if (context instanceof Activity) {
            return get((Activity) context);
        } else if (context instanceof ContextWrapper) {
            return get(((ContextWrapper) context).getBaseContext());
        }
    }

    return getApplicationManager(context);
}
 
源代码19 项目: giffun   文件: RequestManagerRetriever.java
public RequestManager get(FragmentActivity activity) {
    if (Util.isOnBackgroundThread()) {
        return get(activity.getApplicationContext());
    } else {
        assertNotDestroyed(activity);
        FragmentManager fm = activity.getSupportFragmentManager();
        return supportFragmentGet(activity, fm);
    }
}
 
源代码20 项目: giffun   文件: RequestManagerRetriever.java
public RequestManager get(Fragment fragment) {
    if (fragment.getActivity() == null) {
        throw new IllegalArgumentException("You cannot start a load on a fragment before it is attached");
    }
    if (Util.isOnBackgroundThread()) {
        return get(fragment.getActivity().getApplicationContext());
    } else {
        FragmentManager fm = fragment.getChildFragmentManager();
        return supportFragmentGet(fragment.getActivity(), fm);
    }
}
 
源代码21 项目: giffun   文件: RequestManagerRetriever.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public RequestManager get(Activity activity) {
    if (Util.isOnBackgroundThread() || Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        return get(activity.getApplicationContext());
    } else {
        assertNotDestroyed(activity);
        android.app.FragmentManager fm = activity.getFragmentManager();
        return fragmentGet(activity, fm);
    }
}
 
源代码22 项目: giffun   文件: RequestManagerRetriever.java
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public RequestManager get(android.app.Fragment fragment) {
    if (fragment.getActivity() == null) {
        throw new IllegalArgumentException("You cannot start a load on a fragment before it is attached");
    }
    if (Util.isOnBackgroundThread() || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return get(fragment.getActivity().getApplicationContext());
    } else {
        android.app.FragmentManager fm = fragment.getChildFragmentManager();
        return fragmentGet(fragment.getActivity(), fm);
    }
}
 
源代码23 项目: giffun   文件: RequestManager.java
RequestManager(Context context, final Lifecycle lifecycle, RequestManagerTreeNode treeNode,
        RequestTracker requestTracker, ConnectivityMonitorFactory factory) {
    this.context = context.getApplicationContext();
    this.lifecycle = lifecycle;
    this.treeNode = treeNode;
    this.requestTracker = requestTracker;
    this.glide = Glide.get(context);
    this.optionsApplier = new OptionsApplier();

    ConnectivityMonitor connectivityMonitor = factory.build(context,
            new RequestManagerConnectivityListener(requestTracker));

    // If we're the application level request manager, we may be created on a background thread. In that case we
    // cannot risk synchronously pausing or resuming requests, so we hack around the issue by delaying adding
    // ourselves as a lifecycle listener by posting to the main thread. This should be entirely safe.
    if (Util.isOnBackgroundThread()) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                lifecycle.addListener(RequestManager.this);
            }
        });
    } else {
        lifecycle.addListener(this);
    }
    lifecycle.addListener(connectivityMonitor);
}
 
源代码24 项目: giffun   文件: RequestManager.java
/**
 * Performs {@link #resumeRequests()} recursively for all managers that are contextually descendant
 * to this manager based on the Activity/Fragment hierarchy. The hierarchical semantics are identical as for
 * {@link #pauseRequestsRecursive()}.
 */
public void resumeRequestsRecursive() {
    Util.assertMainThread();
    resumeRequests();
    for (RequestManager requestManager : treeNode.getDescendants()) {
        requestManager.resumeRequests();
    }
}
 
源代码25 项目: giffun   文件: Glide.java
/**
 * Clears as much memory as possible.
 *
 * @see android.content.ComponentCallbacks#onLowMemory()
 * @see android.content.ComponentCallbacks2#onLowMemory()
 */
public void clearMemory() {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be cleared before bitmap pool to clear re-pooled Bitmaps too. See #687.
    memoryCache.clearMemory();
    bitmapPool.clearMemory();
}
 
源代码26 项目: giffun   文件: Glide.java
/**
 * Clears some memory with the exact amount depending on the given level.
 *
 * @see android.content.ComponentCallbacks2#onTrimMemory(int)
 */
public void trimMemory(int level) {
    // Engine asserts this anyway when removing resources, fail faster and consistently
    Util.assertMainThread();
    // memory cache needs to be trimmed before bitmap pool to trim re-pooled Bitmaps too. See #687.
    memoryCache.trimMemory(level);
    bitmapPool.trimMemory(level);
}
 
源代码27 项目: giffun   文件: Glide.java
/**
 * Cancel any pending loads Glide may have for the target and free any resources (such as {@link Bitmap}s) that may
 * have been loaded for the target so they may be reused.
 *
 * @param target The Target to cancel loads for.
 */
public static void clear(Target<?> target) {
    Util.assertMainThread();
    Request request = target.getRequest();
    if (request != null) {
        request.clear();
        target.setRequest(null);
    }
}
 
源代码28 项目: giffun   文件: GenericRequestBuilder.java
/**
 * Overrides the {@link Target}'s width and height with the given values. This is useful almost exclusively for
 * thumbnails, and should only be used when you both need a very specific sized image and when it is impossible or
 * impractical to return that size from {@link Target#getSize(com.bumptech.glide.request.target.SizeReadyCallback)}.
 *
 * @param width The width in pixels to use to load the resource.
 * @param height The height in pixels to use to load the resource.
 * @return This request builder.
 */
public GenericRequestBuilder<ModelType, DataType, ResourceType, TranscodeType> override(int width, int height) {
    if (!Util.isValidDimensions(width, height)) {
        throw new IllegalArgumentException("Width and height must be Target#SIZE_ORIGINAL or > 0");
    }
    this.overrideWidth = width;
    this.overrideHeight = height;

    return this;
}
 
源代码29 项目: giffun   文件: BitmapEncoder.java
@Override
public boolean encode(Resource<Bitmap> resource, OutputStream os) {
    final Bitmap bitmap = resource.get();

    long start = LogTime.getLogTime();
    Bitmap.CompressFormat format = getFormat(bitmap);
    bitmap.compress(format, quality, os);
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "Compressed with type: " + format + " of size " + Util.getBitmapByteSize(bitmap) + " in "
                + LogTime.getElapsedMillis(start));
    }
    return true;
}
 
源代码30 项目: giffun   文件: SizeConfigStrategy.java
@Override
public void put(Bitmap bitmap) {
    int size = Util.getBitmapByteSize(bitmap);
    Key key = keyPool.get(size, bitmap.getConfig());

    groupedMap.put(key, bitmap);

    NavigableMap<Integer, Integer> sizes = getSizesForConfig(bitmap.getConfig());
    Integer current = sizes.get(key.size);
    sizes.put(key.size, current == null ? 1 : current + 1);
}
 
 类所在包
 同包方法