프로그램/Android

URL 로 이미지 받아서 모서리 둥근 ImageView 생성

잡식성초보 2016. 9. 26. 17:47



위와 같은 이미지뷰를 받을수 있다.


일단 이미지를 url로 받아서 bitmap으로 변환 후 둥근 모서리각을 줘서 이미지뷰를 만든다.


테두리또한 줄수 있다.



1) 통신을 태워 Bitmap 받기


image01 = (ImageView)mView.findViewById(R.id.image01);

try {
String url = "http://placeimg.com/320/100/any/grayscale"; //이미지 url
Bitmap bitmap = new StringToBitMap().execute(url).get(); //url로 Bitmap 받기
image01.setImageBitmap(CommonUtil.getRoundedCornerBitmap(mContext, bitmap, PixelUtil.dpToPx(mContext, 13))); //context, bitmap, 라운딩정도
} catch (Exception e){
e.printStackTrace();
}
public class StringToBitMap extends AsyncTask<String, Void, Bitmap> {

@Override
protected Bitmap doInBackground(String... params) {
try{
URL url = new URL(params[0]);
HttpURLConnection connection;
connection=(HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
Log.e("getRoundedCornerBitmap" , "bitmap : " + bitmap);
return bitmap;
}catch(Exception e){
Log.e("getRoundedCornerBitmap" , "Exception : " + e.getMessage());
e.getMessage();
return null;
}
}

@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
}
}




2) 둥근 각을 줘서 다시 그린후 Bitmap으로 받기


public static Bitmap getRoundedCornerBitmap(Context ctx, Bitmap bitmap, int rounds) {

Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);

final int color = 0xff424242;
final Paint paint = new Paint(); //이미지가 들어가는 paint
final Rect rect = new Rect(1, 1, bitmap.getWidth()-1, bitmap.getHeight()-1); //테두리1을 주기 위하여 -1
final RectF rectF = new RectF(rect);
final float roundPx = rounds;

paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);

Paint paint2 = new Paint(); //테두리만 그릴 paint
paint2.setAntiAlias(true);
paint2.setStyle(Paint.Style.STROKE);
paint2.setStrokeWidth(PixelUtil.dpToPx(ctx, 1)); //테두리를 준다.
paint2.setColor(Color.parseColor("#009cff"));

canvas.drawRoundRect(rectF, roundPx, roundPx, paint2);

return output;
}



반응형