LoginSignup
5
5

More than 5 years have passed since last update.

AndroidでYouTubeのサムネイルをアス比を直して表示する。

Last updated at Posted at 2015-02-07

何をするのか

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()";
        }

    }

これで無事黒い線を除去することができ高画質なサムネイルを表示することができます。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5