package com.yuqirong.meituanlistview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import com.yuqirong.meituanlistview.R;

/**
 * Created by Anyway on 2016/4/17.
 */
public class MeiTuanOvalView extends View {

    private static final String TAG = "MeiTuanFirstView";
    private float scale;
    private Matrix mMatrix;
    private Paint mPaint;
    private Bitmap mSourceBitmap;
    private Bitmap mDestBitmap;
    private int resultHeight;
    private int resultWidth;

    public MeiTuanOvalView(Context context) {
        this(context, null);
    }

    public MeiTuanOvalView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MeiTuanOvalView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mMatrix = new Matrix();
        mSourceBitmap = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pull_image));
        mDestBitmap = Bitmap.createBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pull_end_image_frame_05));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            resultWidth = widthSize;
        } else {
            resultWidth = mDestBitmap.getWidth();
            if (widthMode == MeasureSpec.AT_MOST) {
                resultWidth = Math.min(mDestBitmap.getWidth(), widthSize);
            }
        }
        resultHeight = resultWidth * mDestBitmap.getHeight() / mDestBitmap.getWidth();
        setMeasuredDimension(resultWidth, resultHeight);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.scale(scale, scale, getWidth() / 2, getHeight() / 2);
        canvas.drawBitmap(mSourceBitmap, 0, getHeight() / 3, mPaint);
    }

    public void setScale(float scale) {
        if (scale > 1) {
            scale = 1;
        } else if (scale < 0) {
            scale = 0;
        }
        this.scale = scale;
        Log.i(TAG, "scale = " + scale);
        invalidate();
    }
}
