Android: создать круговое изображение с пикассо
Вопрос был задан, и было обещано сделать для самой версии Picasso, что я использую: Как отправить круговое растровое изображение в ImageView с помощью Picasso? Я новичок в Picasso, и только то, что я использовал,
Picasso.with(context).load(url).resize(w, h).into(imageview);
Я уже нашел https://gist.github.com/julianshen/5829333, но я не уверен, как совместить его с строкой выше неловким способом.
Ответы
Ответ 1
Изучите немного раньше, поскольку есть доступные ответы. В любом случае, перейдите по этой ссылке и внимательно прочитайте ее, чтобы узнать, как ее использовать.
попробуй это:
import com.squareup.picasso.Transformation;
public class CircleTransform 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 squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
@Override
public String key() {
return "circle";
}
}
тогда просто примените это как:
Picasso.with(activity).load(mayorShipImageLink).transform(new CircleTransform()).into(ImageView);
Ответ 2
здесь есть что-то, что предоставляется библиотекой support-v4! Посмотрите
RoundedBitmapDrawable. Не нужно сворачивать самостоятельно:
Picasso.with(context).load(url)
.resize(w, h)
.into(myImageView, new Callback() {
@Override
public void onSuccess() {
Bitmap imageBitmap = ((BitmapDrawable) myImageView.getDrawable()).getBitmap();
RoundedBitmapDrawable imageDrawable = RoundedBitmapDrawableFactory.create(getResources(), imageBitmap);
imageDrawable.setCircular(true);
imageDrawable.setCornerRadius(Math.max(imageBitmap.getWidth(), imageBitmap.getHeight()) / 2.0f);
myImageView.setImageDrawable(imageDrawable);
}
@Override
public void onError() {
myImageView.setImageResource(R.drawable.default_image);
}
});
Примечание. Пикассо также имеет вызов .transform(customTransformation), который вы могли бы теоретически использовать, однако у меня были проблемы с этим. Это выше. Удачи!
Ответ 3
Еще одна альтернатива, которую я нашел, это библиотека этих парней. Он работает автономно или совместно с Пикассо. Я выбрал маршрут Пикассо, как показано ниже:
https://github.com/vinc3m1/RoundedImageView
Transformation transformation = new RoundedTransformationBuilder()
.borderColor(Color.BLACK)
.borderWidthDp(3)
.cornerRadiusDp(30)
.oval(false)
.build();
Picasso.with(context)
.load(url)
.fit()
.transform(transformation)
.into(imageView);
Работал для меня!
Ответ 4
Я пробовал все решения выше, но ни один из них не дает мне преобразование круга без кадрирования изображения. Это решение будет работать только для изображений с одинаковой шириной и высотой.. это мое решение выше
сначала ------
Picasso.with(getActivity())
.load(url)
.error(R.drawable.image2)
.placeholder(R.drawable.ic_drawer)
.resize(200, 200)
.transform(new ImageTrans_CircleTransform())
.into(imageView1);
тогда сделайте это --------
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Shader.TileMode;
import com.squareup.picasso.Transformation;
public class ImageTrans_CircleTransform implements Transformation {
@Override
public Bitmap transform(Bitmap source) {
if (source == null || source.isRecycled()) {
return null;
}
final int width = source.getWidth() + borderwidth;
final int height = source.getHeight() + borderwidth;
Bitmap canvasBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(source, TileMode.CLAMP, TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
Canvas canvas = new Canvas(canvasBitmap);
float radius = width > height ? ((float) height) / 2f : ((float) width) / 2f;
canvas.drawCircle(width / 2, height / 2, radius, paint);
//border code
paint.setShader(null);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(bordercolor);
paint.setStrokeWidth(borderwidth);
canvas.drawCircle(width / 2, height / 2, radius - borderwidth / 2, paint);
//--------------------------------------
if (canvasBitmap != source) {
source.recycle();
}
return canvasBitmap;
}
@Override
public String key() {
return "circle";
}
}
Ответ 5
Используйте эту библиотеку для создания кругового изображения.
Чтобы сделать круговой ImageView, добавьте эту библиотеку CircularImageView в свой проект
и добавьте CircularImageView в ваш макет XML
<com.pkmmte.view.CircularImageView
android:layout_width="250dp"
android:layout_height="250dp"
android:src="@drawable/image"
app:border_color="#EEEEEE"
app:border_width="4dp"
app:shadow="true" />`
Затем используйте пикассо для загрузки необходимого изображения в это изображение. Picasso делает все кэширование, вам не нужно беспокоиться об этом
Ответ 6
Добавить зависимость Gradle
implementation 'jp.wasabeef:picasso-transformations:2.2.1'
Конец использовать это
Picasso.with(context)
.load(url)
.resize(w, h)
.transform(new CropCircleTransformation())
.into(imageview);
Wiki: Преобразования Пикассо
Ответ 7
Включите xml drawable типа Layer-list с кодом ниже
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/shape_status">
<shape android:shape="oval">
<solid android:color="@android:color/black"/>
</shape>
</item>
<item android:drawable="@drawable/ic_status_content"/></layer-list>
затем используйте xml для вашего ImageView в файле android.src
<ImageView
android:id="@+id/iconStatus"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_gravity="right"
android:src="@drawable/ic_circle_status"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"/>
Ответ 8
Это работало для меня
<com.androidhub4you.crop.RoundedImageView
android:id="@+id/imageView_round"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="15dp"
android:src="@drawable/ic_launcher" />
http://www.androidhub4you.com/2014/10/android-custom-shape-imageview-rounded.html
Ответ 9
Этот работает с текущим снимком Picasso 3:
class CircleTransformation : Transformation {
override fun transform(source: RequestHandler.Result): RequestHandler.Result {
if (source.bitmap == null) {
return source
}
var bitmap: Bitmap
// since we cant transform hardware bitmaps create a software copy first
if (VERSION.SDK_INT >= VERSION_CODES.O && source.bitmap!!.config == Config.HARDWARE) {
val softwareCopy = source.bitmap!!.copy(Config.ARGB_8888, true)
if (softwareCopy == null) {
return source
} else {
bitmap = softwareCopy
source.bitmap!!.recycle()
}
} else {
bitmap = source.bitmap!!
}
var size = bitmap.width
// if bitmap is non-square first create square one
if (size != bitmap.height) {
var sizeX = size
var sizeY = bitmap.height
size = Math.min(sizeY, sizeX)
sizeX = (sizeX - size) / 2
sizeY = (sizeY - size) / 2
val squareSource = Bitmap.createBitmap(bitmap, sizeX, sizeY, size, size)
bitmap.recycle()
bitmap = squareSource
}
val circleBitmap = Bitmap.createBitmap(size, size, Config.ARGB_8888)
val canvas = Canvas(circleBitmap)
val paint = Paint()
val shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.shader = shader
paint.isAntiAlias = true
val centerAndRadius = size / 2f
canvas.drawCircle(centerAndRadius, centerAndRadius, centerAndRadius, paint)
bitmap.recycle()
return RequestHandler.Result(circleBitmap, source.loadedFrom, source.exifRotation)
}
override fun key(): String {
return "circleTransformation()"
}
}
Суть Picasso3: https://gist.github.com/G00fY2/f3fbc468570024930c1fd9eb4cec85a1
Ответ 10
Вот что сработало у меня с Picasso v2.71828
class CircleTransform : Transformation {
override fun transform(source: Bitmap?): Bitmap? {
if (source == null) {
return source
}
var bitmap: Bitmap
// since we cant transform hardware bitmaps create a software copy first
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && source.config == Bitmap.Config.HARDWARE) {
val softwareCopy = source.copy(Bitmap.Config.ARGB_8888, true)
if (softwareCopy == null) {
return source
} else {
bitmap = softwareCopy
source.recycle()
}
} else {
bitmap = source
}
var size = bitmap.width
// if bitmap is non-square first create square one
if (size != bitmap.height) {
var sizeX = size
var sizeY = bitmap.height
size = Math.min(sizeY, sizeX)
sizeX = (sizeX - size) / 2
sizeY = (sizeY - size) / 2
val squareSource = Bitmap.createBitmap(bitmap, sizeX, sizeY, size, size)
bitmap.recycle()
bitmap = squareSource
}
val circleBitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888)
val canvas = Canvas(circleBitmap)
val paint = Paint()
val shader = BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
paint.shader = shader
paint.isAntiAlias = true
val centerAndRadius = size / 2f
canvas.drawCircle(centerAndRadius, centerAndRadius, centerAndRadius, paint)
bitmap.recycle()
return circleBitmap
}
override fun key(): String {
return "circleTransformation()"
}
}