咱們已經成功實現了刮刮獎的功能了,本期是擴展篇,咱們把這個View直接定義成開源控件,發佈到JitPack上,之後有須要也能夠直接使用,關於自定義控件的知識,不瞭解的同窗能夠看這下面我以前寫的這兩篇android
Android開發——發佈第三方庫到JitPack上github
按照以前那一篇自定義控件來操做,咱們創建個atts.xml,在其中定義屬性,這裏,咱們能夠將中獎圖片和信息層顏色合爲一項,遮蓋層圖片和遮蓋層顏色合爲一項canvas
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="GuaJiangView"> <attr name="text" format="string"/> <attr name="textColor" format="color"/> <attr name="textSize" format="integer"/> <attr name="messageBackground" format="color|reference"/> <attr name="cover" format="color|reference"/> <attr name="PaintSize" format="integer"/> <attr name="isDrawText" format="boolean"/> <attr name="clearFlag" format="integer"/> </declare-styleable> </resources>
得到咱們定義的屬性測試
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.GuaJiangView); text = ta.getString(R.styleable.GuaJiangView_text); textColor = ta.getColor(R.styleable.GuaJiangView_textColor,0); textSize = ta.getInteger(R.styleable.GuaJiangView_textSize,16); coverDrawable = ta.getDrawable(R.styleable.GuaJiangView_cover); isDrawText = ta.getBoolean(R.styleable.GuaJiangView_isDrawText,true); clearFlag = ta.getInteger(R.styleable.GuaJiangView_clearFlag,60); if (!isDrawText){ backgroundDrawable = ta.getDrawable(R.styleable.GuaJiangView_messageBackground); } paintSize = ta.getInteger(R.styleable.GuaJiangView_PaintSize,10); ta.recycle();這裏加了個判斷,當用戶選擇只寫中獎信息,咱們能夠屏蔽掉獲取信息層的圖片設置,防止出錯
修改以前的項目代碼優化
開源庫,天然是不能像以前項目那般寫的那麼凌亂,天然是得寫上厚厚的註釋,將代碼重構優化一下,還得考慮到相關的邏輯code
這裏提一下,attrs中可使用\|
來使該屬性接收兩個屬性,最經常使用的仍是背景顏色和背景圖片合成一項,例如上面定義的attr中的背景orm
<attr name="messageBackground" format="color|reference"/>
咱們能夠經過下面的方法來對這樣的屬性使用,得到以後轉換爲bitmapxml
/** * drawable轉換爲bitmap * @param drawable 須要轉換的drawble * @param width 寬 * @param height 高 * @return 返回bitmap */ public Bitmap drawableToBitmap(Drawable drawable, int width, int height) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; }
其實drawable 它自己有一個 draw方法, 只要咱們調用setBounds
設置範圍, 在調用draw
方法就能夠直接畫了,上面的drawable其實已經包含有顏色了,因此咱們直接調用draw
方法便可在畫出一個純顏色的bitmap
簡單地觀察,這裏與會以前的mCanvas是同樣的。
以新建的bitmap做爲畫板,以後drawable在canvas上做畫(其實是畫在了bitmap),以後咱們返回這個bitmap使用便可
其餘地與以前差很少,你們本身琢磨琢磨吧,最後我會發出完整代碼的
上傳github以及JitPack
這裏將很少說什麼了,我這兩篇寫的很清楚了簡單的測試使用
GuaJiangViewDemo
咱們按照文檔上的方法,導入依賴,使用便可
原本想單獨出來寫一篇的,不過,發現也沒有什麼新的代碼要寫,咱們直接拿開源庫來用便可(須要美女穿衣和脫衣的衣服哦~)
我就準備了二次元少女的衣服,將兩張圖片放到drawable文件夾之中,咱們就能夠開始工做了
弄好以後,個人android Studio居然卡死了?!
什麼鬼!!好在重啓一下軟件就行了
激動時刻————
哈哈,成功,刮刮卡項目的詳解就到此結束啦~