图片为 Android 应用增添了急需的上下文和视觉效果。Picasso 让您在应用中轻松加载图片——通常只需一行代码!
Picasso.get().load("https://i.imgur.com/DvpvklR.png").into(imageView);
Android 图片加载中的许多常见陷阱都由 Picasso 自动处理
ImageView
回收和下载取消。自动检测适配器重用并取消之前的下载。
@Override public void getView(int position, View convertView, ViewGroup parent) { SquaredImageView view = (SquaredImageView) convertView; if (view == null) { view = new SquaredImageView(context); } String url = getItem(position); Picasso.get().load(url).into(view); }
转换图片以更好地适应布局并减少内存大小。
Picasso.get() .load(url) .resize(50, 50) .centerCrop() .into(imageView)
您还可以指定自定义转换以实现更高级的效果。
public class CropSquareTransformation implements Transformation { @Override public Bitmap transform(Bitmap source) { int size = Math.min(source.getWidth(), source.getHeight()); int x = (source.getWidth() - size) / 2; int y = (source.getHeight() - size) / 2; Bitmap result = Bitmap.createBitmap(source, x, y, size, size); if (result != source) { source.recycle(); } return result; } @Override public String key() { return "square()"; } }
将此类的实例传递给 transform
方法。
Picasso 支持下载占位符和错误占位符作为可选功能。
Picasso.get() .load(url) .placeholder(R.drawable.user_placeholder) .error(R.drawable.user_placeholder_error) .into(imageView);
请求将在显示错误占位符之前重试三次。
资源、assets、文件、内容提供器都支持作为图片源。
Picasso.get().load(R.drawable.landing_screen).into(imageView1); Picasso.get().load("file:///android_asset/DvpvklR.png").into(imageView2); Picasso.get().load(new File(...)).into(imageView3);
在开发过程中,您可以启用显示彩色指示条,该指示条指示图片来源。在 Picasso 实例上调用 setIndicatorsEnabled(true)
。
Picasso 的源代码、示例以及本网站可在 GitHub 上获取。
<dependency>
<groupId>com.squareup.picasso3</groupId>
<artifactId>picasso</artifactId>
<version>(insert latest version)</version>
</dependency>
implementation 'com.squareup.picasso:picasso:(insert latest version)'
如果您想贡献代码,可以通过在 GitHub 上 fork 仓库并发送 pull request 来实现。
提交代码时,请尽量遵循现有约定和风格,以便代码尽可能保持可读性。另外请确保通过运行 mvn clean verify
来编译您的代码。
在您的代码被项目接受之前,您还必须签署个人贡献者许可协议 (CLA)。
Copyright 2013 Square, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://apache.ac.cn/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.