Android基礎控件——ImageView的自定義,巧用Matrix實現(xiàn)圖片不變形的炫酷PK條

前言

在開發(fā)中常常會遇到PK條制作牡彻,如果在PK條中是純色的情況下扫沼,比較好辦,如下:



我們通常會設置其權(quán)重進行更新兩個PK條的進度庄吼,實現(xiàn)起來也簡單

//更新PkBar寬度比例
private void updateLayoutParams(float ratio) {
    LinearLayout.LayoutParams paramsLeft = (LinearLayout.LayoutParams) mLeftBar.getLayoutParams();
    LinearLayout.LayoutParams paramsRight = (LinearLayout.LayoutParams) mRightBar.getLayoutParams();
    paramsLeft.weight = ratio;
    paramsRight.weight = 1 - ratio;
    mLeftBar.setLayoutParams(paramsLeft);
    mRightBar.setLayoutParams(paramsRight);
}

如果是在純色的基礎上,采用酷炫的圖片進行遮蓋严就,這樣的話总寻,可能會導致素材的壓縮情況,如下:


通過素材的對比梢为,明顯看到是有壓縮的


我們可以通過自定義ImageViewScaleType渐行,通過裁剪達到我們的效果

實現(xiàn)

1、搭建ImageView

通過上面看到铸董,我們會用兩邊都是ImageView去填充祟印,通過設置不用的權(quán)重進行PK進度的更新,為了兼容我們提供四種方向的縮放裁剪模式粟害,而且繼承AppCompatImageView

public class CropImageView extends AppCompatImageView {

    private CropType mCropType;
    private Bitmap mBitmap;

    //提供四種方向的縮放裁剪模式
    public enum CropType {
        LEFT_CROP,
        RIGHT_CROP,
        TOP_CROP,
        BOTTOM_CROP
    }

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

    public CropImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CropImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTypeArray(context, attrs);
        initView();
    }
}

2蕴忆、獲取在xml的屬性

在styleable中聲明我們需要的裁剪模式

<!--CropImageView 裁剪縮放模式-->
<declare-styleable name="CropImageView">
    <attr name="cropType">
        <enum name="leftCrop" value="0" />
        <enum name="rightCrop" value="1" />
        <enum name="topCrop" value="2" />
        <enum name="bottomCrop" value="3" />
    </attr>
</declare-styleable>

接著代碼就是常規(guī)的獲取自定義屬性

private void initTypeArray(Context context, AttributeSet attrs) {
    final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CropImageView);
    int cropType = typedArray.getInt(R.styleable.CropImageView_cropType, -1);
    if (cropType == 0) {
        mCropType = CropType.LEFT_CROP;
    } else if (cropType == 1) {
        mCropType = CropType.RIGHT_CROP;
    } else if (cropType == 2) {
        mCropType = CropType.TOP_CROP;
    } else if (cropType == 3) {
        mCropType = CropType.BOTTOM_CROP;
    }
    typedArray.recycle();
}

3、裁剪ImageView

這里是最重要的一步悲幅,通過閱讀ImageView的源碼套鹅,模仿ScaleType對Matrix進行操作達到我們想要的效果

    if (mCropType != null) {
        updateCropMatrix();
    }
}

private void updateCropMatrix() {
    //如果沒有炫酷PK條就默認設置個縮放模式
    if (mBitmap == null) {
        if (getScaleType() == ScaleType.MATRIX) {
            setScaleType(ScaleType.CENTER_CROP);
        }
        return;
    }
    //真正處理炫酷PK條
    setScaleType(ScaleType.MATRIX);
    Matrix mMatrix = new Matrix();
    float scale = 1; //縮放圖片大小比例
    float dx = 0, dy = 0;
    final int vHeight = getHeight() - getPaddingLeft() - getPaddingRight();//獲取真實高度
    final int vWidth = getWidth() - getPaddingTop() - getPaddingBottom();//獲取真實寬度
    final int dWidth = mBitmap.getWidth();
    final int dHeight = mBitmap.getHeight();

    if (mCropType == CropType.LEFT_CROP) {
        scale = (float) vHeight / (float) dHeight;
        dx = 0;
    } else if (mCropType == CropType.RIGHT_CROP) {
        scale = (float) vHeight / (float) dHeight;
        dx = vWidth - dWidth * scale; //x方向平移,顯示圖片右邊區(qū)域內(nèi)容
    } else if (mCropType == CropType.TOP_CROP) {
        scale = (float) vWidth / (float) dWidth;
        dy = 0;
    } else if (mCropType == CropType.BOTTOM_CROP) {
        scale = (float) vWidth / (float) dWidth;
        dy = vHeight - dHeight * scale; //y方向平移汰具,顯示圖片底邊區(qū)域內(nèi)容
    }
    mMatrix.setScale(scale, scale); //先將圖片寬(或高)縮放到View的同等大小
    mMatrix.postTranslate(Math.round(dx), Math.round(dy));
    setImageMatrix(mMatrix);
}

在真正的操作上卓鹿,你可以理解為CropImageView就是一個View去承載一張Bitmap,由于我們的CropImageView大小是固定不變的留荔,而承載的Bitmap是可以通過縮放等功能進行處理的吟孙,通過移動和縮放Bitmap的大小,如果Bitmap的大小大于原先的CropImageView的大小峦剔,這樣不知不覺之中就形成了Bitmap的裁剪功能

  • Bitmap:包含照片的所有像素信息官研、寬高等其他信息
  • Matrix:Matrix的本質(zhì)是矩陣,通過矩陣的計算可以進行圖片的旋轉(zhuǎn)贴唇、縮放等功能

通過計算炫酷PK條的寬高是否要適配原先ImageView的大小稚失,進行縮放動作栋艳,由于縮放的動作是在CropImageView本身的左上角實現(xiàn)的,我們需要對CropImageView和Bitmap左上角或者右上角的對齊句各,這樣Bitmap才剛好完整的蓋在CropImageView上

  • LEFT_CROP:左上角需要對其吸占,本身就是在左上角進行縮放的,所以不需要平移
  • RIGHT_CROP:右上角需要對其凿宾,所以通過計算CropImageView和Bitmap的寬度差矾屯,進行平移
  • TOP_CROP:左上角需要對其,本身就是在左上角進行縮放的初厚,所以不需要平移
  • BOTTOM_CROP:左下角需要對其件蚕,所以通過計算CropImageView和Bitmap的高度差,進行平移

適配

通過提供接口的形式讓外部調(diào)用产禾,在每次設置變化的時候都會去進行重新計算排作,在onSizeChanged的時候也需要重新計算,這是考慮到父View的大小可能會被外部改變

public void setCropType(CropType cropType) {
    mCropType = cropType;
    updateCropMatrix();
}

@Override
public void setImageBitmap(Bitmap bm) {
    super.setImageBitmap(bm);
    mBitmap = bm;
    updateCropMatrix();
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    updateCropMatrix();
}

使用

1亚情、xml

在xml上配置好最原始的圖片背景色

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cropImg="http://schemas.android.com/apk/res-auto"
    android:id="@+id/ll_pk_bar_bg"
    android:layout_width="match_parent"
    android:layout_height="30dp"
    android:layout_margin="16dp"
    android:layout_centerVertical="true"
    android:orientation="horizontal">

    <com.example.customimage.CropImageView
        android:id="@+id/img_left_bar"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#0caafc"
        cropImg:cropType="leftCrop" />

    <com.example.customimage.CropImageView
        android:id="@+id/img_right_bar"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="#f2a603"
        cropImg:cropType="rightCrop" />
</LinearLayout>

2妄痪、代碼

代碼上去設置我們的炫酷PK條,通過權(quán)重去更新進度

public class MainActivity extends AppCompatActivity {

    private CropImageView mLeftBar;
    private CropImageView mRightBar;

    private float ratio = 0.0f;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ratio += 0.1f;
            updateLayoutParams(ratio);
            if (ratio <= 1.0f) {
                mHandler.sendEmptyMessageDelayed(0, 1000);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        BitmapDrawable leftDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.left_bar);
        Bitmap leftBitmap = leftDrawable.getBitmap();
        BitmapDrawable rightDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.right_bar);
        Bitmap rightBitmap = rightDrawable.getBitmap();

        mLeftBar = findViewById(R.id.img_left_bar);
        mRightBar = findViewById(R.id.img_right_bar);

        mLeftBar.setImageBitmap(leftBitmap);
        mRightBar.setImageBitmap(rightBitmap);

        mHandler.sendEmptyMessageDelayed(0, 1000);
    }

    //更新PkBar寬度比例
    private void updateLayoutParams(float ratio) {
        LinearLayout.LayoutParams paramsLeft = (LinearLayout.LayoutParams) mLeftBar.getLayoutParams();
        LinearLayout.LayoutParams paramsRight = (LinearLayout.LayoutParams) mRightBar.getLayoutParams();
        paramsLeft.weight = ratio;
        paramsRight.weight = 1 - ratio;
        mLeftBar.setLayoutParams(paramsLeft);
        mRightBar.setLayoutParams(paramsRight);
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末楞件,一起剝皮案震驚了整個濱河市衫生,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌土浸,老刑警劉巖罪针,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異黄伊,居然都是意外死亡泪酱,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進店門毅舆,熙熙樓的掌柜王于貴愁眉苦臉地迎上來西篓,“玉大人,你說我怎么就攤上這事憋活∑窠颍” “怎么了?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵悦即,是天一觀的道長吮成。 經(jīng)常有香客問我橱乱,道長,這世上最難降的妖魔是什么粱甫? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任泳叠,我火速辦了婚禮,結(jié)果婚禮上茶宵,老公的妹妹穿的比我還像新娘危纫。我一直安慰自己,他們只是感情好乌庶,可當我...
    茶點故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布种蝶。 她就那樣靜靜地躺著,像睡著了一般瞒大。 火紅的嫁衣襯著肌膚如雪螃征。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天透敌,我揣著相機與錄音盯滚,去河邊找鬼。 笑死酗电,一個胖子當著我的面吹牛魄藕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播撵术,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼泼疑,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了荷荤?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤移稳,失蹤者是張志新(化名)和其女友劉穎蕴纳,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體个粱,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡古毛,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了都许。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片稻薇。...
    茶點故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖胶征,靈堂內(nèi)的尸體忽然破棺而出塞椎,到底是詐尸還是另有隱情,我是刑警寧澤睛低,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布案狠,位于F島的核電站服傍,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏骂铁。R本人自食惡果不足惜吹零,卻給世界環(huán)境...
    茶點故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望拉庵。 院中可真熱鬧灿椅,春花似錦、人聲如沸钞支。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽伸辟。三九已至麻惶,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間信夫,已是汗流浹背窃蹋。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留静稻,地道東北人警没。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像振湾,于是被迫代替她去往敵國和親杀迹。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,066評論 2 355

推薦閱讀更多精彩內(nèi)容