下面列出了怎么用com.bumptech.glide.request.target.SimpleTarget的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_WHAT_SHOW_NETWORK_IMAGE:
String url = msg.getData().getString("url");
RequestOptions requestOptions = RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.RESOURCE)
.override(150, 150)
.placeholder(R.mipmap.ic_launcher);
Glide.with(getActivity()).asBitmap().load(url)
.apply(requestOptions)
.thumbnail(0.5F)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
// OutputStream outputStream = null;
// bitmap.compress(Bitmap.CompressFormat.JPEG, 50, outputStream);
mImageView.setImageBitmap(bitmap);
}
});
break;
}
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_WHAT_SHOW_NETWORK_IMAGE:
String url = msg.getData().getString("url");
RequestOptions requestOptions = RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.RESOURCE)
.override(150, 150)
.placeholder(R.mipmap.ic_launcher);
Glide.with(getActivity()).asBitmap().load(url)
.apply(requestOptions)
.thumbnail(0.5F)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
// mImageView.setImageBitmap(CommonUtil.toRoundCorner(bitmap, 100));
mImageView.setImageBitmap(bitmap);
}
});
break;
}
}
private void updateBackground(String uri) {
RequestOptions options = new RequestOptions()
.centerCrop()
.error(mDefaultBackground);
Glide.with(this)
.asBitmap()
.load(uri)
.apply(options)
.into(new SimpleTarget<Bitmap>(mMetrics.widthPixels, mMetrics.heightPixels) {
@Override
public void onResourceReady(
Bitmap resource,
Transition<? super Bitmap> transition) {
mBackgroundManager.setBitmap(resource);
}
});
}
private void saveToSystemGallery(final String name, int id) {
GlideApp.with(this).downloadOnly().load(id).into(new SimpleTarget<File>() {
@Override
public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), name + ".jpg");
try {
FileUtils.copyFile(resource, file);
showMessage("保存图片成功了", TastyToast.SUCCESS);
notifySystemGallery(file);
} catch (IOException e) {
e.printStackTrace();
showMessage("保存图片失败了", TastyToast.ERROR);
}
}
});
}
private void displayImage() {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 对图片进行设置 但不形成示例,不耗费内存
BitmapFactory.decodeFile(mImageFile.getPath(), options);
int imageRequestWidth = getRequestImeWidth();
int imageRequestHeight = getRequestImeHeight(options);
Logger.d("width " + imageRequestWidth + " height:" + imageRequestHeight);
Logger.d("bitmap1 width " + options.outWidth + " height:" + options.outHeight);
Glide.with(mView.getActivity())
.load(mImageFile)
.asBitmap()
.override(imageRequestWidth, imageRequestHeight) // 设置大小
.fitCenter() // 不按照比例
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
//根据Bitmap对象创建ImageSpan对象
Logger.d("bitmap width:" + resource.getWidth() + " height:" + resource.getHeight());
mView.insertImage(mImageName, resource);
}
});
}
private void loadImageView() {
final String url = getArguments().getString(ARGUMENTS_IMAGE);
Glide.with(this).downloadOnly().load(url)
/* todo replace error icon */
.apply(new RequestOptions().error(R.mipmap.qq_refresh_success))
.into(new SimpleTarget<File>() {
@Override
public void onResourceReady(File resource, Transition<? super File> transition) {
mImageView.setImage(ImageSource.uri(Uri.fromFile(resource)));
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
}
});
}
/**
* Download the pictures
* @param path
* @param listeners
*/
public static void downloadImage(String path, final OnDownloadTarget listeners){
Glide.with(BaseApplication.getInstance())
.load(path)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
File file=BitmapUtil.getInstance().bitmapSavePath(resource);
String pathLocal = file.getAbsolutePath();
listeners.finish(pathLocal);
}
@Override
public void onLoadFailed(Exception e, Drawable errorDrawable) {
super.onLoadFailed(e, errorDrawable);
listeners.error();
}
});
}
private void loadImage(String imageTitle) {
int maxImageSide = presenter.calcMaxImageSide();
ImageUtil.loadImageWithSimpleTarget(GlideApp.with(this),
PostManager.getInstance(this.getApplicationContext()).getOriginImageStorageRef(imageTitle),
new SimpleTarget<Bitmap>(maxImageSide, maxImageSide) {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
progressBar.setVisibility(View.GONE);
touchImageView.setImageBitmap(resource);
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
super.onLoadFailed(errorDrawable);
progressBar.setVisibility(View.GONE);
touchImageView.setImageResource(R.drawable.ic_stub);
}
});
}
@Override
public void saveInPhone() {
super.saveInPhone();
final MsgDefinBean bean = baseEntity.getMsgDefinBean();
String local = TextUtils.isEmpty(bean.getContent()) ? bean.getUrl() : bean.getContent();
Glide.with(BaseApplication.getInstance())
.load(local)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
File file = FileUtil.createAbsNewFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/connect/" + bean.getMessage_id() + FileUtil.FileType.IMG.getFileType());
MediaStore.Images.Media.insertImage(context.getContentResolver(), resource, "connect", "");
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
}
});
}
private void updateAlbum(String uri) {
if (uri != null && uri.startsWith("http")) {
uri = MusicUtil.getRealUrl(uri, DensityUtil.toDp(50));
}
if (getContext() != null) {
Glide.with(this).asBitmap().load(uri).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
bg.setBackground(BlurBitmapUtil.createBlurredImageFromBitmap(resource, getContext(), 20));
}
});
BaseApplication.getAppComponent().getImageLoader().loadImage(getContext(), new GlideImageLoaderConfig.Builder()
.imageView(album).url(uri).build());
}
}
protected void updateBackground(String uri) {
int width = mMetrics.widthPixels;
int height = mMetrics.heightPixels;
Glide.with(getActivity())
.load(uri)
.centerCrop()
.error(mDefaultBackground)
.into(new SimpleTarget<GlideDrawable>(width, height) {
@Override
public void onResourceReady(GlideDrawable resource,
GlideAnimation<? super GlideDrawable>
glideAnimation) {
mBackgroundManager.setDrawable(resource);
}
});
mBackgroundTimer.cancel();
}
@Override
public boolean onBindItem(PickerItem item, boolean create, int i) {
Artist artist = mData.get(i);
item.setTitle(artist.getName());
item.setRadiusUnit(PhysicsEngine.INSTANCE.interpolate(1,2f,((float) artist.getSongCount())/getItemCount()));
// Glide
ArtistGlideRequest.Builder.from(GlideApp.with(mContext), artist)
// .tryToLoadOriginal(true)
.generateBuilder(mContext)
.buildRequestDrawable()
.centerCrop()
// .error(R.drawable.music_style)
.into(new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
item.setBackgroundImage(resource);
}
});
return true;
}
@Override
public boolean onBindItem(PickerItem item, boolean create, int i) {
super.onBindItem(item,create,i);
Genre genre = mData.get(i);
item.setTitle(genre.name);
item.setRadiusUnit(genre.songCount);
// Glide
ArrayList<Song> songs = GenreLoader.getSongs(mContext,genre.id);
Glide.with(mContext).load(MusicUtil.getMediaStoreAlbumCoverUri(songs.get(0).albumId)).into(new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
item.setBackgroundImage(resource);
GenrePickerAdapter.this.notifyBackImageUpdated(i);
}
});
return true;
}
@Override
public boolean onBindItem(PickerItem item, boolean create, int i) {
super.onBindItem(item,create,i);
Song song = mData.get(i);
item.setTitle(song.title);
item.setRadiusUnit(PickerItem.SIZE_RANDOM);
// Glide
Glide.with(mContext).load(MusicUtil.getMediaStoreAlbumCoverUri(song.albumId)).into(new SimpleTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
item.setBackgroundImage(resource);
SongPickerAdapter.this.notifyBackImageUpdated(i);
}
});
return true;
}
public static void loadImgBackground(Object obj, final View v, SimpleTarget simpleTarget) {
DrawableTypeRequest drawableTypeRequest = getDrawableTypeRequest(obj, v);
if (drawableTypeRequest == null) {
drawableTypeRequest = getDrawableTypeRequest(sCommonPlaceholder, v);
}
if (drawableTypeRequest != null) {
drawableTypeRequest
.asBitmap()
.centerCrop()
.dontAnimate()
.error(sCommonPlaceholder)
.placeholder(sCommonPlaceholder)
.diskCacheStrategy(DiskCacheStrategy.RESULT)
.into(simpleTarget != null ? simpleTarget : new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
BitmapDrawable drawable = new BitmapDrawable(resource);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
v.setBackground(drawable);
} else {
v.setBackgroundDrawable(drawable);
}
}
});
}
}
private void replaceImage(final String imageName) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
File imageFile = new File(mView.getActivity().getExternalFilesDir(mNoteId).getPath() + "/" + imageName);
BitmapFactory.decodeFile(imageFile.getPath(), options);
int imageRequestWidth = getRequestImeWidth();
int imageRequestHeight = setNeedHeight(options);
Glide.with(mView.getActivity())
.load(imageFile)
.asBitmap()
.override(imageRequestWidth, imageRequestHeight)
.fitCenter()
.priority(Priority.HIGH)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
mView.replaceImage(imageName, resource);
}
});
}
private void initializeBackground(Movie movie) {
mDetailsBackground.enableParallax();
Glide.with(getActivity())
.load(movie.getBackgroundImage())
.asBitmap()
.centerCrop()
.error(R.drawable.assistant_tv_banner)
.into(
new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(
Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
mDetailsBackground.setCoverBitmap(bitmap);
mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size());
}
});
}
@Override
public void onBindViewHolder(final ContributorAdapter.ViewHolder holder, int position) {
ContributorData contributor = contributors.get(position);
Glide.with(holder.imageView.getContext()).asBitmap().load(contributor.imageUrl).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
holder.imageView.setImageBitmap(resource);
}
});
holder.textView.setText(contributor.name);
holder.itemView.setTag(contributor);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (view.getTag() != null && view.getTag() instanceof ContributorData)
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(((ContributorData) view.getTag()).url)));
}
});
}
private void onCaptureClicked() {
orderEnforcer.reset();
Stopwatch fastCaptureTimer = new Stopwatch("Capture");
camera.capture((jpegData, frontFacing) -> {
fastCaptureTimer.split("captured");
Transformation<Bitmap> transformation = frontFacing ? new MultiTransformation<>(new CenterCrop(), new FlipTransformation())
: new CenterCrop();
GlideApp.with(this)
.asBitmap()
.load(jpegData)
.transform(transformation)
.override(cameraPreview.getWidth(), cameraPreview.getHeight())
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
fastCaptureTimer.split("transform");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resource.compress(Bitmap.CompressFormat.JPEG, 80, stream);
fastCaptureTimer.split("compressed");
byte[] data = stream.toByteArray();
fastCaptureTimer.split("bytes");
fastCaptureTimer.stop(TAG);
controller.onImageCaptured(data, resource.getWidth(), resource.getHeight());
}
@Override
public void onLoadFailed(@Nullable Drawable errorDrawable) {
controller.onCameraError();
}
});
});
}
private void refreshData(Topic topic) {
topicTitleTextView.setText(topic.getTitle());
topicContentTextView.setText(topic.getContent());
String imgFullUrl = NetConstant.RESOURCES_BASE + topic.getImg();
Glide.with(this).asBitmap().load(imgFullUrl).into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
// topicImageView.setImageBitmap(CommonUtil.toRoundCorner(bitmap, bitmap.getWidth()));
topicImageView.setImageBitmap(bitmap);
}
});
}
public static void resizeImage(Activity activity, Uri uri, int width_px, int height_px, Intent adv) {
Glide.with(activity)
.asBitmap()
.load(uri)
.into(new SimpleTarget<Bitmap>(width_px, height_px) {
@Override
public void onResourceReady(@NonNull Bitmap bitmap, Transition<? super Bitmap> transition) {
saveResizedImage(bitmap, activity, uri, adv);
}
});
}
private void loadAndSetBackgroundImageParameter(VideoEntity selectedVideo,
final Activity activity, DisplayMetrics metrics,
final BackgroundManager backgroundManager, RequestOptions defaultPlaceHolder,
Drawable defualtDrawble) {
if (selectedVideo == null) {
return;
}
String url1 = selectedVideo.getVideoBgImageLocalStorageUrl();
String url2 = selectedVideo.getBgImageUrl();
String loadedUri;
if (url1.isEmpty()) {
loadedUri = url2;
} else {
loadedUri = url1;
}
// wait until runtime the activity has window
if (!backgroundManager.isAttached()) {
backgroundManager.attach(activity.getWindow());
}
// glide on error
Glide.with(activity)
.asBitmap()
.load(loadedUri)
.apply(defaultPlaceHolder)
.into(new SimpleTarget<Bitmap>(metrics.widthPixels, metrics.heightPixels) {
@Override
public void onResourceReady(Bitmap resource,
Transition<? super Bitmap> glideAnimation) {
backgroundManager.setDrawable(
new BitmapDrawable(activity.getResources(), resource));
}
});
}
private void loadAndSetVideoCardImage() {
String loadedUri = findLocalContentUriOrNetworkUrl(CARD);
Glide.with(this)
.asBitmap()
.load(loadedUri)
.apply(mDefaultPlaceHolder)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(final Bitmap resource,
Transition<? super Bitmap> glideAnimation) {
mDescriptionOverviewRow.setImageBitmap(getActivity(), resource);
}
});
setSelectedPosition(0, false);
}
protected void updateBackgroundImage(String uri) {
int width = mMetrics.widthPixels;
int height = mMetrics.heightPixels;
Glide.with(getActivity())
.load(uri)
.into(new SimpleTarget<Drawable>(width, height) {
@Override
public void onResourceReady(Drawable resource,
Transition<? super Drawable> glideAnimation) {
mBackgroundManager.setDrawable(resource);
}
});
mHandler.removeCallbacks(mBackgroudUpdateRunnable);
}
@Override
public void prefetch(Uri uri) {
mRequestManager
.load(uri)
.downloadOnly(new SimpleTarget<File>() {
@Override
public void onResourceReady(File resource,
GlideAnimation<? super File> glideAnimation) {
// not interested in result
}
});
}
public static void loadImageWithSimpleTarget(GlideRequests glideRequests, String url, SimpleTarget<Bitmap> simpleTarget) {
glideRequests.asBitmap()
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.fitCenter()
.into(simpleTarget);
}
private void showSavePictureDialog( String imageUrl) {
final String saveUrl;
if (imageUrl.contains("_")){
saveUrl=imgUrl.split("_")[0];
}else {
saveUrl=imageUrl;
}
QMUIDialog.MenuDialogBuilder builder = new QMUIDialog.MenuDialogBuilder(this);
builder.addItem("保存原图", (dialog, which) -> {
GlideApp.with(PhotoImageActivity.this).downloadOnly().load(Uri.parse(saveUrl)).into(new SimpleTarget<File>() {
@Override
public void onResourceReady(@NonNull File resource, @Nullable Transition<? super File> transition) {
File filePath = new File(SDCardUtils.DOWNLOAD_IMAGE_PATH);
if (!filePath.exists()) {
if (!filePath.mkdirs()) {
showMessage("创建文件夹失败了", TastyToast.ERROR);
return;
}
}
File file = new File(filePath, UUID.randomUUID().toString() + ".jpg");
try {
FileUtils.copyFile(resource, file);
showMessage("保存图片成功了", TastyToast.SUCCESS);
notifySystemGallery(file);
} catch (IOException e) {
e.printStackTrace();
showMessage("保存图片失败了", TastyToast.ERROR);
}
}
});
dialog.dismiss();
});
builder.show();
}
private void addHeader(final OnlineMusicList onlineMusicList) {
adapter.removeAllHeader();
adapter.addHeader(new RecyclerArrayAdapter.ItemView() {
@Override
public View onCreateView(ViewGroup parent) {
return getLayoutInflater().inflate(R.layout.header_online_music, parent, false);
}
@Override
public void onBindView(View view) {
final ImageView iv_header_bg = (ImageView) view.findViewById(R.id.iv_header_bg);
final ImageView iv_cover = (ImageView) view.findViewById(R.id.iv_cover);
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
TextView tv_update_date = (TextView) view.findViewById(R.id.tv_update_date);
TextView tv_comment = (TextView) view.findViewById(R.id.tv_comment);
tv_title.setText(onlineMusicList.getBillboard().getName());
tv_update_date.setText(getString(R.string.recent_update, onlineMusicList.getBillboard().getUpdate_date()));
tv_comment.setText(onlineMusicList.getBillboard().getComment());
Glide.with(OnlineMusicActivity.this)
.load(onlineMusicList.getBillboard().getPic_s640())
.asBitmap()
.placeholder(R.drawable.default_cover)
.error(R.drawable.default_cover)
.override(200, 200)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
iv_cover.setImageBitmap(resource);
iv_header_bg.setImageBitmap(ImageUtils.blur(resource));
}
});
}
});
}
@Override
public void loadImage(String url,final ImageView iv) {
Glide.with(iv.getContext())
.load(url)
.into(new SimpleTarget<Drawable>(200, 200) {
@Override
public void onResourceReady(Drawable resource,
Transition<? super Drawable> transition) {
iv.setImageDrawable(resource);
}
});
}
private void glide() {
isStoragePermissionGranted();
Glide.with(mContext)
.asBitmap()
.load("http://image.tmdb.org/t/p/original"+poster_url)
.into(new SimpleTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
saveImage(resource);
}
});
}