2014-01-13 47 views
1

我在这里和其他互联网上仔细搜索过,但没有找到解决方案。 我有固定大小的ImageView。我需要显示一些位图,在运行时加载。它们都有不同的尺寸和长宽比。例如:ImageView是480x270px的位图可以是160x90,1600x500,50x100等等。我希望它们能够集中在ImageView中并适合它们。圆角。带有圆角的Android ImageView(再次)

两种最流行的方法是(1)处理位图和(2)修改imageView子类中的绘制阶段。

Romain Guy扩展Drawable并在Canvas中使用drawRoundRect方法。不幸的是,他的解决方案不适用FIT_CENTER,尽管圆角线很锐利。

还有一种处理位图的方式,将其渲染到另一个位图并四舍五入。将它设置为源 - 获取中心和适合的ImageView。但是在这种情况下,舍入矩形仅在位图的像素网格中存在。如果位图很小,可能会非常模糊。

最后一个解决方案,最适合我,但也需要升级。我们可以调整画布以沿其边框包含clipPath。但是具有16/5纵横比的居中位图不会被四舍五入 - 它将被绘制在cliPath之外。

回答

3

所以,我完成了here的回答,所以它可以解决我的问题。

XML:

<RoundedThumb 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"/> 

JAVA:

public class RoundedThumb extends ImageView { 

private final float radius = getContext().getResources().getDimension(R.dimen.corner_radius); 
private RectF mSrcRect = new RectF(); 
private RectF mDstRect = new RectF(); 
private Path mClipPath = new Path(); 

public RoundedThumb(Context context) { 
    super(context); 
} 

public RoundedThumb(Context context, AttributeSet attrs) { 
    super(context, attrs); 
} 

public RoundedThumb(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
} 

protected void onDraw(Canvas canvas) { 
    if (getDrawable() != null && getImageMatrix() != null) { 
     mSrcRect.set(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight()); 
     getImageMatrix().mapRect(mDstRect, mSrcRect); 
     mClipPath.reset(); 
     mClipPath.addRoundRect(mDstRect, radius, radius, Path.Direction.CW); 
     canvas.clipPath(mClipPath); 
    } 
    super.onDraw(canvas); 
} 
} 

与用法:

thumb.setScaleType(ImageView.ScaleType.FIT_CENTER); 
Bitmap thumbnail = BitmapFactory.decodeFile(path); 
thumb.setImageBitmap(thumbnail); 

所以,现在矩形的路径转化就像BitmapDrawable内的ImageView,始终准确地周围包围ImageView中的任何位图。对我来说重要的是 - ImageView仍然具有aspectRatio 16/9,并在资源中定义它的位置。但是位图有四舍五入的边框,但没有修改。

UPD1:我有点困惑:不幸的是在某些设备上clipPath方法没有效果(SII)甚至崩溃(旧的华硕变压器)。可以通过将hardwareAccelerated设置为false来完全修复。但是,该死的,这是不好的=/

+0

与hardwareAccelerated真相同:( – Marabita

+0

最后我从资源中删除hardwareAccelerated,只是放在try/catch onDraw。 – mjollneer