我创建了一个基于this answer的圆形imageView。 它使图像完美圆润。但是,我有两个问题。
我正在使用的课程:
public class RoundImageView extends ImageView {
private Path path;
private Paint paint;
private PorterDuffXfermode porterDuffXfermode;
public RoundImageView(Context context) {
super(context);
init();
}
public RoundImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setWillNotDraw(false);
path = new Path();
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
porterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.DST_IN);
}
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.TRANSPARENT);
// Create a circular path.
final float halfWidth = canvas.getWidth()/2;
final float halfHeight = canvas.getHeight()/2;
final float radius = Math.max(halfWidth, halfHeight);
path.addCircle(halfWidth, halfHeight, radius, Path.Direction.CCW);
paint.setXfermode(porterDuffXfermode);
canvas.drawPath(path, paint);
}
}
我在布局中添加它的方式:
<com.allstarxi.widget.RoundImageView
android:layout_width="35dp"
android:layout_height="35dp"
android:src="@drawable/ic_launcher"
android:id="@+id/imageView"
android:contentDescription="@string/general_content_description"
android:scaleType="center" />
这是截图:
答案 0 :(得分:0)
尝试将它放在RoundImageView类中:
public Bitmap getCroppedBitmap(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());
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
// canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
bitmap.getWidth() / 2, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
//Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
//return _bmp;
return output;
}
然后把它放在onDraw:
getCroppedBitmap(BitmapFactory.decodeResource(getResources(), getDrawable()));
答案 1 :(得分:0)
因为我找不到如何解决这个问题,所以我使用了RoundedImageView library。修复imageView的宽度和高度时很好。 这是我的样本:
<com.makeramen.RoundedImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="36dp"
android:layout_height="36dp"
android:src="@drawable/ic_launcher"
android:id="@+id/ivUserPic"
android:contentDescription="@string/general_content_description"
android:scaleType="centerCrop"
app:mutate_background="true"
app:border_width="0dp"
app:corner_radius="18dp"
app:oval="true"/>
答案 2 :(得分:0)
之前我有过相同的经历,因为我在UI Thread中从数据库加载了一些东西,你是否在UI Thread中从数据库/磁盘加载了什么?如果是,则需要使用AsynTask加载它,否则会影响UI渲染过程
答案 3 :(得分:-1)
关于这一切:android:scaleType="center"
从此处尝试另一个scaleTypes并查看结果:
CENTER, CENTER_CROP, CENTER_INSIDE, FIT_CENTER, FIT_END, FIT_START, FIT_XY, MATRIX