\$\begingroup\$
\$\endgroup\$
I've followed this blog to get images with nice pretty rounded corners in Android.
I've managed to strip out a lot of the superfluous arrayAdapter
stuff and make it much more simple.
I've largely tweaked this just until I made it work. Does anyone have any feedback?
class StreamDrawable extends Drawable {
private final float mCornerRadius;
private final RectF mRect = new RectF();
private final BitmapShader mBitmapShader;
private final Paint mPaint;
private final int mMargin;
StreamDrawable(Bitmap bitmap, float cornerRadius, int margin) {
mCornerRadius = cornerRadius;
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setShader(mBitmapShader);
mMargin = margin;
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
mRect.set(mMargin, mMargin, bounds.width() - mMargin, bounds.height() - mMargin);
}
@Override
public void draw(Canvas canvas) {
canvas.drawRoundRect(mRect, mCornerRadius, mCornerRadius, mPaint);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
mPaint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter cf) {
mPaint.setColorFilter(cf);
}
}
public void drawit(){
final int CORNER_RADIUS = 24; // dips
final int MARGIN = 12; // dips
final int mCornerRadius;
final int mMargin;
final float density = this.getResources().getDisplayMetrics().density;
mCornerRadius = (int) (CORNER_RADIUS * density + 0.5f);
mMargin = (int) (MARGIN * density + 0.5f);
ImageView imgvw = (ImageView) findViewById(R.id.imageView2);
Bitmap myBitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.london);
Bitmap resizedBitmap = Bitmap.createScaledBitmap(myBitmap, imgvw.getWidth(), imgvw.getHeight(), false);
StreamDrawable d = new StreamDrawable(resizedBitmap, mCornerRadius, mMargin);
imgvw.setBackground(d);
}
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
1 Answer 1
\$\begingroup\$
\$\endgroup\$
1
This looks very clean to me. Except perhaps:
imgvw
- that's disemvoweling. nd t's bd. Not to mention it's breaking your camelCasing convention for locals.drawit
- while the name says what the function does, I would avoid DoThatThing names and perhaps go for a more soberrender
method name, if not justdraw
.
Lastly, I don't know Java well enough to know if it's convention, but I wouldn't use that m
prefix.
answered Nov 20, 2013 at 2:27
-
\$\begingroup\$ The
m
prefix is a convention in Java :) (sometimes used, sometimes not. But there's nothing wrong with using it) \$\endgroup\$Simon Forsberg– Simon Forsberg2013年11月20日 14:20:08 +00:00Commented Nov 20, 2013 at 14:20
lang-java