ImageView округлые углы
Я хотел, чтобы изображение имело закругленные углы. Я реализую этот xml-код и использую его в своем представлении изображения. но изображение перекрывает форму. Я загружаю изображение с помощью async-задачи.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<corners android:radius="20dip" />
</shape>
<ImageView
android:id="@+id/trVouchersImage"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_marginLeft="8dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_alignParentLeft="true"
android:background="@drawable/ash_arrow"
/>
Ответы
Ответ 1
Я использую библиотеку загрузчика Universal Image для загрузки и округления углов изображения, и это сработало для меня.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(thisContext)
// You can pass your own memory cache implementation
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.build();
DisplayImageOptions options = new DisplayImageOptions.Builder()
.displayer(new RoundedBitmapDisplayer(10)) //rounded corner bitmap
.cacheInMemory(true)
.cacheOnDisc(true)
.build();
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
imageLoader.displayImage(image_url,image_view, options );
Ответ 2
ПРОСТОЙ ПОДХОД:
Создайте XML файл rounded_fg.xml в папке res/drawable/ вашего приложения. Содержимое файла roundnded_fg.xml выглядит следующим образом:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadiusRatio="2"
android:shape="ring"
android:thicknessRatio="1"
android:useLevel="false">
<gradient
android:type="radial"
android:gradientRadius="8dp"
android:endColor="@color/white"
/>
</shape>
Вы можете сопоставить endColor с фоновым макетом контейнера ImageView, а градиент Radius может иметь любое значение в соответствии с вашими требованиями (<= 36dp).
Теперь используйте этот объект в качестве переднего плана для вашего изображения следующим образом:
<ImageView
android:layout_width="55dp"
android:layout_height="55dp"
android:foreground="@drawable/rounded_fg" />
Прекрасно работает с квадратными изображениями и/или изображениями.
Квадратное изображение /ImageView:
![Square Image/ImageView]()
Прямоугольное изображение /ImageView:
![Rectangular Image/ImageView]()
Передний план применяется над кнопкой:
![Foreground applied over a button]()
Ответ 3
вы можете делать по XML таким образом
<stroke android:width="3dp"
android:color="#ff000000"/>
<padding android:left="1dp"
android:top="1dp"
android:right="1dp"
android:bottom="1dp"/>
<corners android:radius="30px"/>
и прагматически вы можете создать округленное растровое изображение и установить в ImageView.
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 12;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
Для Универсального ленивого загрузчика вы также можете использовать этот wat.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.displayer(new RoundedBitmapDisplayer(25)) // default
.build();
Ответ 4
NEW ANSWER
Для этого используйте библиотеку Glide. Этот lib также рекомендуется Google. См. Как объединить изображение с помощью библиотеки Glide?
OLD ANSWER
Просто добавьте это изображение в cardView
и установите высоту рамки карты на 0dp... будет делать трюк (в моем случае был viewPager
с изображениями), просто замените viewPager
на ImageView
):
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="250dp"
app:cardElevation="0dp">
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.CardView>
Ответ 5
Вы должны использовать RoundedCornersTransformation
из эту библиотеку и создать круговой ImageView
.
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import com.squareup.picasso.Transformation;
public class RoundedCornersTransformation implements Transformation {
public enum CornerType {
ALL,
TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT,
TOP, BOTTOM, LEFT, RIGHT,
OTHER_TOP_LEFT, OTHER_TOP_RIGHT, OTHER_BOTTOM_LEFT, OTHER_BOTTOM_RIGHT,
DIAGONAL_FROM_TOP_LEFT, DIAGONAL_FROM_TOP_RIGHT
}
private int mRadius;
private int mDiameter;
private int mMargin;
private CornerType mCornerType;
public RoundedCornersTransformation(int radius, int margin) {
this(radius, margin, CornerType.ALL);
}
public RoundedCornersTransformation(int radius, int margin, CornerType cornerType) {
mRadius = radius;
mDiameter = radius * 2;
mMargin = margin;
mCornerType = cornerType;
}
@Override public Bitmap transform(Bitmap source) {
int width = source.getWidth();
int height = source.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
drawRoundRect(canvas, paint, width, height);
source.recycle();
return bitmap;
}
private void drawRoundRect(Canvas canvas, Paint paint, float width, float height) {
float right = width - mMargin;
float bottom = height - mMargin;
switch (mCornerType) {
case ALL:
canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
break;
case TOP_LEFT:
drawTopLeftRoundRect(canvas, paint, right, bottom);
break;
case TOP_RIGHT:
drawTopRightRoundRect(canvas, paint, right, bottom);
break;
case BOTTOM_LEFT:
drawBottomLeftRoundRect(canvas, paint, right, bottom);
break;
case BOTTOM_RIGHT:
drawBottomRightRoundRect(canvas, paint, right, bottom);
break;
case TOP:
drawTopRoundRect(canvas, paint, right, bottom);
break;
case BOTTOM:
drawBottomRoundRect(canvas, paint, right, bottom);
break;
case LEFT:
drawLeftRoundRect(canvas, paint, right, bottom);
break;
case RIGHT:
drawRightRoundRect(canvas, paint, right, bottom);
break;
case OTHER_TOP_LEFT:
drawOtherTopLeftRoundRect(canvas, paint, right, bottom);
break;
case OTHER_TOP_RIGHT:
drawOtherTopRightRoundRect(canvas, paint, right, bottom);
break;
case OTHER_BOTTOM_LEFT:
drawOtherBottomLeftRoundRect(canvas, paint, right, bottom);
break;
case OTHER_BOTTOM_RIGHT:
drawOtherBottomRightRoundRect(canvas, paint, right, bottom);
break;
case DIAGONAL_FROM_TOP_LEFT:
drawDiagonalFromTopLeftRoundRect(canvas, paint, right, bottom);
break;
case DIAGONAL_FROM_TOP_RIGHT:
drawDiagonalFromTopRightRoundRect(canvas, paint, right, bottom);
break;
default:
canvas.drawRoundRect(new RectF(mMargin, mMargin, right, bottom), mRadius, mRadius, paint);
break;
}
}
private void drawTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter),
mRadius, mRadius, paint);
canvas.drawRect(new RectF(mMargin, mMargin + mRadius, mMargin + mRadius, bottom), paint);
canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
}
private void drawTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius,
mRadius, paint);
canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
canvas.drawRect(new RectF(right - mRadius, mMargin + mRadius, right, bottom), paint);
}
private void drawBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom),
mRadius, mRadius, paint);
canvas.drawRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom - mRadius), paint);
canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
}
private void drawBottomRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius,
mRadius, paint);
canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
canvas.drawRect(new RectF(right - mRadius, mMargin, right, bottom - mRadius), paint);
}
private void drawTopRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right, bottom), paint);
}
private void drawBottomRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin, mMargin, right, bottom - mRadius), paint);
}
private void drawLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom), paint);
}
private void drawRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom), paint);
}
private void drawOtherTopLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius,
paint);
canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
}
private void drawOtherTopRightRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius,
paint);
canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, right, bottom), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin + mRadius, mMargin, right, bottom - mRadius), paint);
}
private void drawOtherBottomLeftRoundRect(Canvas canvas, Paint paint, float right, float bottom) {
canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius,
paint);
canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, bottom), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mRadius, bottom), paint);
}
private void drawOtherBottomRightRoundRect(Canvas canvas, Paint paint, float right,
float bottom) {
canvas.drawRoundRect(new RectF(mMargin, mMargin, right, mMargin + mDiameter), mRadius, mRadius,
paint);
canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, bottom), mRadius, mRadius,
paint);
canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
}
private void drawDiagonalFromTopLeftRoundRect(Canvas canvas, Paint paint, float right,
float bottom) {
canvas.drawRoundRect(new RectF(mMargin, mMargin, mMargin + mDiameter, mMargin + mDiameter),
mRadius, mRadius, paint);
canvas.drawRoundRect(new RectF(right - mDiameter, bottom - mDiameter, right, bottom), mRadius,
mRadius, paint);
canvas.drawRect(new RectF(mMargin, mMargin + mRadius, right - mDiameter, bottom), paint);
canvas.drawRect(new RectF(mMargin + mDiameter, mMargin, right, bottom - mRadius), paint);
}
private void drawDiagonalFromTopRightRoundRect(Canvas canvas, Paint paint, float right,
float bottom) {
canvas.drawRoundRect(new RectF(right - mDiameter, mMargin, right, mMargin + mDiameter), mRadius,
mRadius, paint);
canvas.drawRoundRect(new RectF(mMargin, bottom - mDiameter, mMargin + mDiameter, bottom),
mRadius, mRadius, paint);
canvas.drawRect(new RectF(mMargin, mMargin, right - mRadius, bottom - mRadius), paint);
canvas.drawRect(new RectF(mMargin + mRadius, mMargin + mRadius, right, bottom), paint);
}
@Override public String key() {
return "RoundedTransformation(radius=" + mRadius + ", margin=" + mMargin + ", diameter="
+ mDiameter + ", cornerType=" + mCornerType.name() + ")";
}
}
Ответ 6
-
Возможно, вы нашли свое решение, но недавно я нашел новую библиотеку, которая позволяет вам создавать любую фигуру, которую вы хотите установить в Изображение VIew.
- Загрузите библиотеку из здесь
- Определите Xml как: -
-
<com.makeramen.roundedimageview.RoundedImageView......... app:riv_corner_radius="Yourradiusdip"/>
- И наслаждайтесь кодированием.! эта библиотека, которую я нашел, является лучшей! благодаря
[Я отправил этот ответ позже, но недавно использовал его и нашел, что это действительно полезно]
Ответ 7
вот что я нашел отсюда: github
сделал небольшую импровизацию. Очень просто и чисто. Нет внешних файлов или методов:
public class RoundedImageView extends ImageView {
private float mCornerRadius = 10.0f;
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attributes) {
super(context, attributes);
}
@Override
protected void onDraw(Canvas canvas) {
// Round some corners betch!
Drawable myDrawable = getDrawable();
if (myDrawable!=null && myDrawable instanceof BitmapDrawable && mCornerRadius > 0) {
Paint paint = ((BitmapDrawable) myDrawable).getPaint();
final int color = 0xff000000;
Rect bitmapBounds = myDrawable.getBounds();
final RectF rectF = new RectF(bitmapBounds);
// Create an off-screen bitmap to the PorterDuff alpha blending to work right
int saveCount = canvas.saveLayer(rectF, null,
Canvas.MATRIX_SAVE_FLAG |
Canvas.CLIP_SAVE_FLAG |
Canvas.HAS_ALPHA_LAYER_SAVE_FLAG |
Canvas.FULL_COLOR_LAYER_SAVE_FLAG |
Canvas.CLIP_TO_LAYER_SAVE_FLAG);
// Resize the rounded rect we'll clip by this view current bounds
// (super.onDraw() will do something similar with the drawable to draw)
getImageMatrix().mapRect(rectF);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, mCornerRadius, mCornerRadius, paint);
Xfermode oldMode = paint.getXfermode();
// This is the paint already associated with the BitmapDrawable that super draws
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
super.onDraw(canvas);
paint.setXfermode(oldMode);
canvas.restoreToCount(saveCount);
} else {
super.onDraw(canvas);
}
}
}
Ответ 8
Просто интересно, нужно ли кому-то еще это сделать.
Для них: вы можете использовать RoundedBitmapDrawable
для своей цели.
Пример кода:
ImageView profilePic = (ImageView) findViewById(R.idimageView);
RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(this.getResources(),bitmap);
roundedBitmapDrawable.setCircular(true);
profilePic.setImageDrawable(roundedBitmapDrawable);
где bitmap
- это изображение, которое вы хотите загрузить в imageView.
Ответ 9
прост, насколько это возможно, используя этот метод util
/*
* [email protected] imageView is your image you want to bordered it
*/
public static Bitmap generateBorders(ImageView imageView){
Bitmap mbitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
Bitmap imageRounded = Bitmap.createBitmap(mbitmap.getWidth(), mbitmap.getHeight(), mbitmap.getConfig());
Canvas canvas = new Canvas(imageRounded);
Paint mpaint = new Paint();
mpaint.setAntiAlias(true);
mpaint.setShader(new BitmapShader(mbitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP));
canvas.drawRoundRect((new RectF(0, 0, mbitmap.getWidth(), mbitmap.getHeight())), 100, 100, mpaint);// Round Image Corner 100 100 100 100
return imageRounded;
}
затем установите растровое изображение в виде изображения с возвращенным значением.
Ответ 10
Попробуйте это, если вам нужно получить округленное изображение.
Ваш класс MainActivity.java
public class MainActivity extends Activity {
private static final int REQUEST_CODE = 1;
private Bitmap bitmap;
private ImageView imageView;
Bitmap roundedBitmapImage;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.result);
}
public void pickImage(View View) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK)
try {
// We need to recycle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
InputStream stream = getContentResolver().openInputStream(
data.getData());
bitmap = BitmapFactory.decodeStream(stream);
stream.close();
/* Bitmap bitmap1=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Bitmap bitmap2=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
Bitmap resultingImage=Bitmap.createBitmap(320, 480, bitmap1.getConfig());
Canvas canvas = new Canvas(resultingImage);
Paint paint = new Paint();
paint.setAntiAlias(true);
Path path=new Path();
path.lineTo(150, 0);
path.lineTo(230, 120);
path.lineTo(70, 120);
path.lineTo(150, 0);
canvas.drawPath(path, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap2, 0, 0, paint);*/
//-------> compositeImageView.setImageBitmap(resultingImage);
// Use this when to provide any shape to image i.e Fit image to any shape.
// under mentioned taking reference from Rounder class. Finally changing image in round shape.
// Here we are passing reference bitmap.
roundedBitmapImage = new Rounder().getRoundedShape(bitmap);
imageView.setImageBitmap(roundedBitmapImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
}
И ваш круглый класс.
/** Этот класс обрезает изображение до круглой формы */
public class Rounder {
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 125;
int targetHeight = 125;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}
}
Ответ 11
нашел легкий путь..
круглое изображение с пользовательским радиусом определения:
http://shortcutsandroid.blogspot.in/2015/02/round-image-view-in-android.html
просто добавьте imageView.setRadius();
//он установит радиус для round imageView.
Ответ 12
Используйте этот пользовательский ImageView в Xml
public class RoundedCornerImageView extends ImageView {
public RoundedCornerImageView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth(), h = getHeight();
Bitmap roundBitmap = getRoundedCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getRoundedCroppedBitmap(Bitmap bitmap, int radius) {
Bitmap finalBitmap;
if (bitmap.getWidth() != radius || bitmap.getHeight() != radius)
finalBitmap = Bitmap.createScaledBitmap(bitmap, radius, radius,
false);
else
finalBitmap = bitmap;
Bitmap output = Bitmap.createBitmap(finalBitmap.getWidth(),
finalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
final RectF rectf = new RectF(0, 0, finalBitmap.getWidth(),
finalBitmap.getHeight());
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor("#BAB399"));
//Set Required Radius Here
int yourRadius = 7;
canvas.drawRoundRect(rectf, yourRadius, yourRadius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(finalBitmap, rect, rect, paint);
return output;
}
}
Ответ 13
Glide отлично работал у меня, я мог бы установить радиус границы в любой угол и все четыре стороны изображения. Это расширение для Glide, которые вам также нужны как зависимость https://github.com/wasabeef/glide-transformations:
Он также поддерживает различные типы масштабирования imageView, которые необходимо использовать должным образом: https://github.com/wasabeef/glide-transformations/issues/32
Ответ 14
Ваш MainActivity.java
выглядит следующим образом:
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
ImageView iv = (ImageView) findViewById(R.id.iv);
Сначала вы должны получить изображение из ресурса как Bitmap
или Drawable
.
Если получится как Bitmap
:
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.ash_arrow);
bm = new Newreza().setEffect(bm, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageBitmap(bm);
Или, если получится как Drawable
:
Drawable d = getResources().getDrawable(R.drawable.ash_arrow);
d = new Newreza().setEffect(d, 0.2f, ((ColorDrawable) ll.getBackground).getColor);
iv.setImageDrawable(d);
Затем создайте новый файл как Newreza.java
рядом с MainActivity.java
и скопируйте нижние коды в Newreza.java
:
package your.package.name;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
//Telegram:@newreza
//mail:[email protected]
public class Newreza{
int a,x,y;
float bmr;
public Bitmap setEffect(Bitmap bm,float radius,int color){
bm=bm.copy(Bitmap.Config.ARGB_8888,true);
bmr=radius*bm.getWidth();
for(y=0;y<bmr;y++){
a=(int)(bmr-Math.sqrt(y*(2*bmr-y)));
for(x=0;x<a;x++){
bm.setPixel(x,y,color);
}
}
for(y=0;y<bmr;y++){
a=(int)(bm.getWidth()-bmr+Math.sqrt(y*(2*bmr-y)));
for(x=a;x<bm.getWidth();x++){
bm.setPixel(x,y,color);
}
}
for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
a=(int)(bm.getWidth()-bmr+Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
for(x=a;x<bm.getWidth();x++){
bm.setPixel(x,y,color);
}
}
for(y=(int)(bm.getHeight()-bmr);y<bm.getHeight();y++){
a=(int)(bmr-Math.sqrt(Math.pow(bmr,2)-Math.pow(bmr+y-bm.getHeight(),2)));
for(x=0;x<a;x++){
bm.setPixel(x,y,color);
}
}
return bm;
}
public Drawable setEffect(Drawable d,float radius,int color){
return new BitmapDrawable(Resources.getSystem(),setEffect(((BitmapDrawable)d).getBitmap(),radius,color));
}
}
Просто обратите внимание, что замените имя пакета первой строкой в коде.
Это% 100 работает, потому что написано в деталях:)
Ответ 15
попробуйте это
http://www.techrepublic.com/article/pro-tip-round-corners-on-an-android-imageview-with-this-hack/
Это сработало отлично.:)
Ответ 16
Я использую расширение ImageView:
public class RadiusCornerImageView extends android.support.v7.widget.AppCompatImageView {
private int cornerRadiusDP = 0; // dp
private int corner_radius_position;
public RadiusCornerImageView(Context context) {
super(context);
}
public RadiusCornerImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RadiusCornerImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray typeArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.RadiusCornerImageView, 0, 0);
try {
cornerRadiusDP = typeArray.getInt(R.styleable.RadiusCornerImageView_corner_radius_dp, 0);
corner_radius_position = typeArray.getInteger(R.styleable.RadiusCornerImageView_corner_radius_position, 0);
} finally {
typeArray.recycle();
}
}
@Override
protected void onDraw(Canvas canvas) {
float radiusPx = AndroidUtil.dpToPx(getContext(), cornerRadiusDP);
Path clipPath = new Path();
RectF rect = null;
if (corner_radius_position == 0) { // all
// round corners on all 4 angles
rect = new RectF(0, 0, this.getWidth(), this.getHeight());
} else if (corner_radius_position == 1) {
// round corners only on top left and top right
rect = new RectF(0, 0, this.getWidth(), this.getHeight() + radiusPx);
} else {
throw new IllegalArgumentException("Unknown corner_radius_position = " + corner_radius_position);
}
clipPath.addRoundRect(rect, radiusPx, radiusPx, Path.Direction.CW);
canvas.clipPath(clipPath);
super.onDraw(canvas);
}
}
Ответ 17
Основываясь на ответе Нихала (fooobar.com/questions/112924/...), здесь приведена версия в формате чистого XML, которая дает прямоугольник с закругленными углами по API 24 и выше. На API 24 ниже он не будет отображать закругленные углы.
Использование:
<ImageView
android:id="@+id/thumbnail"
android:layout_width="150dp"
android:layout_height="200dp"
android:foreground="@drawable/rounded_corner_mask"/>
rounded_corner_mask.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:gravity="bottom|right">
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="@dimen/rounding_radius"
android:height="@dimen/rounding_radius"
android:viewportWidth="10.0"
android:viewportHeight="10.0">
<path
android:pathData="M0,10 A10,10 0 0,0 10,0 L10,10 Z"
android:fillColor="@color/white"/>
</vector>
</item>
<item
android:gravity="bottom|left">
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="@dimen/rounding_radius"
android:height="@dimen/rounding_radius"
android:viewportWidth="10.0"
android:viewportHeight="10.0">
<path
android:pathData="M0,0 A10,10 0 0,0 10,10 L0,10 Z"
android:fillColor="@color/white"/>
</vector>
</item>
<item
android:gravity="top|left">
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="@dimen/rounding_radius"
android:height="@dimen/rounding_radius"
android:viewportWidth="10.0"
android:viewportHeight="10.0">
<path
android:pathData="M10,0 A10,10 0 0,0 0,10 L0,0 Z"
android:fillColor="@color/white"/>
</vector>
</item>
<item
android:gravity="top|right">
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="@dimen/rounding_radius"
android:height="@dimen/rounding_radius"
android:viewportWidth="10.0"
android:viewportHeight="10.0">
<path
android:pathData="M10,10 A10,10 0 0,0 0,0 L10,0 Z"
android:fillColor="@color/white"/>
</vector>
</item>
</layer-list>
Ответ 18
Вы можете использовать библиотеку roundedImageView очень просто:
compile 'com.makeramen:roundedimageview:2.3.0'
а потом:
<com.makeramen.roundedimageview.RoundedImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/img_episode"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="7dp"
app:riv_border_color="@color/colorPrimary"
app:riv_border_width="1dip"
app:riv_corner_radius="10dip"
app:riv_mutate_background="true"
/>
Ответ 19
Создать Drawable XML файл
'<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="@android:color/white" />
<stroke
android:width="1dp"
android:color="@color/md_white_1000" />
'
В вашем макете вы добавляете рисование в качестве фона в imageView.
'<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/photo"
android:background="@drawable/roundcorners"/>'
Затем вы добавляете эту строку в свой код Java.
'ImageView.setClipToOutline(true);'
Примечание: это работает только с уровнем 21+
Ответ 20
Вы можете использовать этот код:
public class StartActivity extends AppCompatActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageView iv = new ImageView(this);
//Create and load images (immutable, typically)
Bitmap source = BitmapFactory.decodeResource(getResources(), R.drawable.dog);
//Create a *mutable* location, and a canvas to draw into it
Bitmap result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
RectF rect = new RectF(0,0,source.getWidth(),source.getHeight());
float radius = 25.0f;
paint.setColor(Color.RED);
canvas.drawRoundRect(rect, radius, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(source, 0, 0, paint);
iv.setImageBitmap(result);
setContentView(iv);
}
}