何をするのか
YouTube Data API v3
でYouTubeのサムネイルを表示しようとした時に取得可能な画像サイズ(Small:120×90
, Medium:320×120
, High:480×360
) しかし、SmallとMediumはアスペクト比が16:9なのに対し、最も肝心で、最も使いたい、Highの画像のアスペクト比が4:3なのです。 そのためそのままImageView
に組み込むと、画像の上下に黒い帯が入ってしまいます。
今回はこの問題をAndroidの画像表示用オープンソースライブラリPicasso
を使って解決しましたので、書き残したいと思います。 例として動画の検索結果をリスト表示するときに使えるように、ArrayAdapter
を継承したクラス内にPicasso
を使った画像取得処理を導入しました。
ソース
CustomAdapter.java
public class CustomAdapter extends ArrayAdapter<VideoItems> {
private LayoutInflater layoutInflater;
private Context context;
public CustomAdapter(Context context, int textViewResourceId, List<VideoItems> objects, RequestQueue queue) {
super(context, textViewResourceId, objects);
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.context = context;
}
static class ViewHolder {
ImageView image;
TextView numView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
VideoItems videoItems = getItem(position);
String thumbnailurl = videoItems.snippet.thumbnails.high.url;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_search, parent, false);
holder = new ViewHolder();
holder.image = (ImageView) convertView.findViewById(R.id.iv_thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//Picassoはこの1行で実装できます。
Picasso.with(context).load(thumbnailurl).transform(new CropTransformer()).placeholder(R.drawable.thumback).error(android.R.drawable.ic_dialog_alert).into(holder.image);
return convertView;
}
private class CropTransformer implements Transformation{
@Override
public Bitmap transform(Bitmap source){
int width = source.getWidth();
int height = source.getHeight();
//width, height = (480, 360)
int x = 0;
//y座標の始点をセットする。
int y = (height-width*9/16)/2;
//幅をそのままに、高さを計算する。
height = width*9/16;
Bitmap result = Bitmap.createBitmap(source, x, y, width, height);
if(result!=source){
source.recycle();
}
return result;
}
@Override
public String key(){
return "Custom()";
}
}
これで無事黒い線を除去することができ高画質なサムネイルを表示することができます。