本章目錄
- Part One:構(gòu)造方法
- Part Two:自定義屬性
- Part Three:布局測量
- Part Four:繪制
- Part Five:重繪
在了解了自定義View的基本繪制流程后番宁,還需要大量的練習去鞏固這方面的知識好爬,所以這一節(jié)我們再練習個下雪案例。
Part One:構(gòu)造方法
構(gòu)造方法的寫法還是老樣子笋轨,沒有啥改變的:
public class SnowView extends View{
public SnowView(Context context) {
this(context, null);
}
public SnowView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initAttrs(context, attrs);
}
private void initAttrs(Context context, AttributeSet attrs) {
}
}
需要注意的是霎终,這里需要把app的gradle中的minSDK改為21(android5.0)角寸。如果想適配更低版本的手機叹誉,也就是說想要在android5.0以下的手機上運行糖埋,需要把4個參數(shù)的構(gòu)造方法刪除,在3個參數(shù)的構(gòu)造方法里使用super和初始化屬性哼转。
Part Two:自定義屬性
下面開始正式畫了明未,如果不太清楚如何下手的話,可以先把問題簡單化壹蔓,跑通了趟妥,再給它復雜化。比如說本例佣蓉,一群雪花不會披摄,那就先處理一朵雪花的情況。
假設我們需要繪制一朵大小隨機勇凭,出現(xiàn)的位置隨機的雪花疚膊,要處理的屬性有什么:
- int minSize:雪花大小隨機值下限
- int maxSize:雪花大小隨機值上限
- Bitmap snowSrc:雪花的圖案
- int moveX:雪花每次移動的橫向距離,也就是橫向移動速度
- int moveY:雪花每次移動的縱向距離虾标,也就是縱向移動速度
前三個屬性都好理解寓盗,后兩個移動屬性可能有的人會有點疑惑,先來看看屏幕坐標璧函。
屏幕的左上角是起點(0傀蚌,0),
- X軸坐標從起點位置向右是正數(shù)蘸吓,向左是負數(shù)
- Y軸坐標從起點位置向下是正數(shù)喳张,向上是負數(shù)
如果我們雪花從屏幕頂端出現(xiàn),想要實現(xiàn)一個移動的效果美澳, 就是在一個固定時間內(nèi)(比如20 - 50毫秒),改變圖片的X軸和Y軸的值摸航,重繪制跟。如此反復循環(huán)就造成雪花的移動效果了。
好了酱虎,意義明白了雨膨,接下來就是把這些屬性初始化了。
attrs.xml中:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="SnowView">
<attr name="minSize" format="integer"/>
<attr name="maxSize" format="integer"/>
<attr name="snowSrc" format="reference|integer"/>
<attr name="moveX" format="integer"/>
<attr name="moveY" format="integer"/>
</declare-styleable>
</resources>
SnowView中:
public class SnowView extends View{
private int minSize; //雪花大小隨機值下限
private int maxSize; //雪花大小隨機值上限
private Bitmap snowSrc; //雪花的圖案
private int moveX; //雪花每次移動的橫向距離读串,也就是橫向移動速度
private int moveY; //雪花每次移動的縱向距離聊记,也就是縱向移動速度
public SnowView(Context context) {
this(context, null);
}
public SnowView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initAttrs(context, attrs);
}
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SnowView, 0, 0);
minSize = typedArray.getInt(R.styleable.SnowView_minSize, 48);//獲取最小值,默認48
maxSize = typedArray.getInt(R.styleable.SnowView_maxSize, 72);//獲取最大值恢暖,默認72
int srcId = typedArray.getResourceId(R.styleable.SnowView_snowSrc, R.drawable.snow_flake);//獲取默認圖片資源ID
snowSrc = BitmapFactory.decodeResource(getResources(), srcId);//根據(jù)資源ID生成Bitmap對象
moveX = typedArray.getInt(R.styleable.SnowView_moveX, 10);//獲取X軸移動速度
moveY = typedArray.getInt(R.styleable.SnowView_moveY, 10);//獲取Y軸移動速度
if (minSize > maxSize){
maxSize = minSize;
}
typedArray.recycle();//TypedArray共享資源排监,資源回收
}
}
activity_main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.terana.mycustomview.MainActivity">
<com.terana.mycustomview.cutstomview.SnowView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:minSize="16"
app:maxSize="48"
app:snowSrc="@drawable/snow_ball"
app:moveX="10"
app:moveY="10"/>
</RelativeLayout>
Part Three:布局測量
測量我們之前說過,除了MeasureSpec.AT_MOST這種杰捂,也就是包裹內(nèi)容需要根據(jù)情況設定個默認值舆床,其它的寫法完全可以一樣,可以照搬。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getDefaultMeasureSizes(getSuggestedMinimumWidth(), widthMeasureSpec, true);
int height = getDefaultMeasureSizes(getSuggestedMinimumHeight(), heightMeasureSpec, false);
setMeasuredDimension(width, height);
}
private int getDefaultMeasureSizes(int suggestedMinimumSize, int defaultMeasureSpec, boolean flag) {
int result = suggestedMinimumSize;
int specMode = MeasureSpec.getMode(defaultMeasureSpec);
int specSize = MeasureSpec.getSize(defaultMeasureSpec);
switch (specMode){
case MeasureSpec.UNSPECIFIED:
result = suggestedMinimumSize;
break;
case MeasureSpec.AT_MOST:
if (flag){
result = snowSrc.getWidth() + getPaddingLeft() +getPaddingRight();
}else {
result = snowSrc.getHeight() + getPaddingTop() +getPaddingBottom();
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
其實從實際情況來說挨队,本例只需要讓SnowView全屏才比較適合谷暮,即便不寫測量布局,默認就是全屏顯示盛垦,只不過寫上更規(guī)范一些湿弦。
Part Four:繪制
好了,準備工作都做好了腾夯,可以正式開始畫圖了颊埃。
繪制工作很簡單,就是在onDraw方法里調(diào)用drawBitmap方法即可俯在,它有四個參數(shù):
- Bitmap bitmap:需要繪制的位圖竟秫,就是我們自定義的snowSrc。
- Rect src:就是位圖的原始區(qū)域跷乐,比如說想動態(tài)改變原圖的大小會調(diào)用肥败,本例用null就可以了,即不對原圖做任何改變愕提。
- RectF dst:位圖要放置在屏幕的區(qū)域馒稍,比如正中央或者屏幕頂端之類的。
- Paint paint:畫筆浅侨,不多說了纽谒,本例沒有啥特性繪制的東西,直接new一個默認即可如输。
暫時先把雪花畫一個固定位置鼓黔,比如屏幕的中心頂部:
public class SnowView extends View{
private int minSize; //雪花大小隨機值下限
private int maxSize; //雪花大小隨機值上限
private Bitmap snowSrc; //雪花的圖案
private int moveX; //雪花每次移動的橫向距離,也就是橫向移動速度
private int moveY; //雪花每次移動的縱向距離不见,也就是縱向移動速度
private Paint snowPaint;
public SnowView(Context context) {
this(context, null);
}
public SnowView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initAttrs(context, attrs);
initVariables();
}
private void initVariables() {
snowPaint = new Paint();
}
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SnowView, 0, 0);
minSize = typedArray.getInt(R.styleable.SnowView_minSize, 48);//獲取最小值澳化,默認48
maxSize = typedArray.getInt(R.styleable.SnowView_maxSize, 72);//獲取最大值,默認72
int srcId = typedArray.getResourceId(R.styleable.SnowView_snowSrc, R.drawable.snow_flake);//獲取默認圖片資源ID
snowSrc = BitmapFactory.decodeResource(getResources(), srcId);//根據(jù)資源ID生成Bitmap對象
moveX = typedArray.getInt(R.styleable.SnowView_moveX, 10);//獲取X軸移動速度
moveY = typedArray.getInt(R.styleable.SnowView_moveY, 10);//獲取Y軸移動速度
if (minSize > maxSize){
maxSize = minSize;
}
typedArray.recycle();//TypedArray共享資源稳吮,資源回收
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getDefaultMeasureSizes(getSuggestedMinimumWidth(), widthMeasureSpec, true);
int height = getDefaultMeasureSizes(getSuggestedMinimumHeight(), heightMeasureSpec, false);
setMeasuredDimension(width, height);
}
private int getDefaultMeasureSizes(int suggestedMinimumSize, int defaultMeasureSpec, boolean flag) {
int result = suggestedMinimumSize;
int specMode = MeasureSpec.getMode(defaultMeasureSpec);
int specSize = MeasureSpec.getSize(defaultMeasureSpec);
switch (specMode){
case MeasureSpec.UNSPECIFIED:
result = suggestedMinimumSize;
break;
case MeasureSpec.AT_MOST:
if (flag){
result = snowSrc.getWidth() + getPaddingLeft() +getPaddingRight();
}else {
result = snowSrc.getHeight() + getPaddingTop() +getPaddingBottom();
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
RectF rectF = new RectF();
//暫時畫在屏幕的中心頂部
rectF.left = getWidth() / 2;
rectF.top = 0;
rectF.right = rectF.left +snowSrc.getWidth();
rectF.bottom = rectF.top +snowSrc.getHeight();
canvas.drawBitmap(snowSrc, null, rectF, snowPaint);
}
}
運行下缎谷,看下結(jié)果:
Part Five:重繪
一個靜止的單雪花已經(jīng)繪制出來了,下面就該讓它動起來灶似,并且位置隨機了列林。
先前的自定義View篇,我們是在外部通過handler傳遞消息并重繪酪惭。這次換個方式希痴,在SnowView的內(nèi)部使用handler。但是撞蚕,需要注意的是润梯,此處最好不使用new Handler來創(chuàng)建對象了,因為View的內(nèi)部自帶一個Handler。
另外纺铭,在Part Four中把初始位置寫死了寇钉,要想改變此位置,需要定義變量出來舶赔,并在onSizeChanged里面完成初始化扫倡,代碼如下
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawSnow(canvas);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
currentX = w / 2;
}
private int currentX;
private int currentY = 0;
private void drawSnow(Canvas canvas) {
//暫時畫在屏幕的中心頂部
rectF.left = currentX;
rectF.top = currentY;
rectF.right = rectF.left +snowSrc.getWidth();
rectF.bottom = rectF.top +snowSrc.getHeight();
canvas.drawBitmap(snowSrc, null, rectF, snowPaint);
getHandler().postDelayed(new Runnable() {
@Override
public void run() {
moveSknowFlake();
invalidate();
}
}, 20);
}
private void moveSknowFlake() {
currentX = currentX + moveX;
currentY = currentY + moveY;
//判斷如果雪花移出屏幕左側(cè),右側(cè)或者下側(cè)竟纳,則回到起始位置重新開始
if (currentX > getWidth() || currentX < 0 || currentY > getHeight()){
currentX = getWidth() / 2;
currentY = 0;
}
}
現(xiàn)在的結(jié)果是一朵雪花從固定位置開始撵溃,以固定的速度到固定位置結(jié)束。
最后一步優(yōu)化就是把這些都隨機化锥累。
完整的SnowView代碼為:
package com.terana.mycustomview.cutstomview;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import com.terana.mycustomview.R;
import java.util.Random;
public class SnowView extends View{
private int minSize; //雪花大小隨機值下限
private int maxSize; //雪花大小隨機值上限
private Bitmap snowSrc; //雪花的圖案
private int moveX; //雪花每次移動的橫向距離缘挑,也就是橫向移動速度
private int moveY; //雪花每次移動的縱向距離,也就是縱向移動速度
private Paint snowPaint;
private RectF rectF;
public SnowView(Context context) {
this(context, null);
}
public SnowView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public SnowView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
initAttrs(context, attrs);
initVariables();
}
private void initVariables() {
snowPaint = new Paint();
rectF = new RectF();
}
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SnowView, 0, 0);
minSize = typedArray.getInt(R.styleable.SnowView_minSize, 48);//獲取最小值桶略,默認48
maxSize = typedArray.getInt(R.styleable.SnowView_maxSize, 72);//獲取最大值语淘,默認72
int srcId = typedArray.getResourceId(R.styleable.SnowView_snowSrc, R.drawable.snow_flake);//獲取默認圖片資源ID
snowSrc = BitmapFactory.decodeResource(getResources(), srcId);//根據(jù)資源ID生成Bitmap對象
moveX = typedArray.getInt(R.styleable.SnowView_moveX, 10);//獲取X軸移動速度
moveY = typedArray.getInt(R.styleable.SnowView_moveY, 10);//獲取Y軸移動速度
if (minSize > maxSize){
maxSize = minSize;
}
typedArray.recycle();//TypedArray共享資源,資源回收
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getDefaultMeasureSizes(getSuggestedMinimumWidth(), widthMeasureSpec, true);
int height = getDefaultMeasureSizes(getSuggestedMinimumHeight(), heightMeasureSpec, false);
setMeasuredDimension(width, height);
}
private int getDefaultMeasureSizes(int suggestedMinimumSize, int defaultMeasureSpec, boolean flag) {
int result = suggestedMinimumSize;
int specMode = MeasureSpec.getMode(defaultMeasureSpec);
int specSize = MeasureSpec.getSize(defaultMeasureSpec);
switch (specMode){
case MeasureSpec.UNSPECIFIED:
result = suggestedMinimumSize;
break;
case MeasureSpec.AT_MOST:
if (flag){
result = snowSrc.getWidth() + getPaddingLeft() +getPaddingRight();
}else {
result = snowSrc.getHeight() + getPaddingTop() +getPaddingBottom();
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
drawSnow(canvas);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
currentX = new Random().nextInt(w);//初始位置為屏幕寬度中的一個隨機值
currentY = -(new Random().nextInt(h));//初始位置為屏幕的上方的隨機值际歼,不可見
}
private int currentX;
private int currentY;
private void drawSnow(Canvas canvas) {
//暫時畫在屏幕的中心頂部
rectF.left = currentX;
rectF.top = currentY;
rectF.right = rectF.left +snowSrc.getWidth();
rectF.bottom = rectF.top +snowSrc.getHeight();
canvas.drawBitmap(snowSrc, null, rectF, snowPaint);
getHandler().postDelayed(new Runnable() {
@Override
public void run() {
moveSknowFlake();
invalidate();
}
}, 20);
}
private boolean moveDirection = true;
private void moveSknowFlake() {
if (moveDirection){
currentX = currentX + (new Random().nextInt(4) + moveX);//速度為一個初始隨機值 + 設定橫移速度
}else {
currentX = currentX - (new Random().nextInt(4) + moveX);//速度為一個初始隨機值 + 設定橫移速度
}
currentY = currentY + (new Random().nextInt(4) + moveY);//速度為一個初始隨機值 + 設定豎移速度
//判斷如果雪花移出屏幕左側(cè)惶翻,右側(cè)或者下側(cè),則回到起始位置重新開始
if (currentX > getWidth() || currentX < 0 || currentY > getHeight()){
currentX = new Random().nextInt(getWidth());
currentY = 0;
moveDirection = !moveDirection;//暫時互相取反鹅心,后面再隨機移動方向
}
}
}
效果為:
由于沒有引入創(chuàng)建雪花對象吕粗,很多地方的代碼比較生澀,效果也很一般旭愧。下一節(jié)會在現(xiàn)有基礎上完成完整的下雪效果颅筋,其實關鍵的代碼都已經(jīng)實現(xiàn)。剩下的無非就是再創(chuàng)建個對象输枯,用數(shù)組去繪制而已垃沦。