編輯:關於 Android 程式設計
做個能即時改字色的功能,需要一個好用的顏色選擇器。下面從「一張七彩圖」開始,一路做到可套用到 TextView 的 ColorPickerDialog。
常見的調色盤長這樣:


右邊那條亮度調色柱則是這樣:

概念清楚之後,程式碼就好寫了:
// 創建七彩圖片
private void init() {
int[] oc = { 0xffff0000, 0xffffff00, 0xff00ff00, 0xff00ffff,
0xff0000ff, 0xffff00ff, 0xffff0000 };
float[] op = { 0, 0.16667f, 0.33333f, 0.5f, 0.66667f, 0.83333f, 1 };
LinearGradient lg = new LinearGradient(0, 0, ORIWIDTH, 0, oc, op, TileMode.MIRROR);
LinearGradient lg2 = new LinearGradient(0, 0, 0, ORIHEIGHT,
0x00808080, 0xff808080, TileMode.MIRROR);
oriColor = Bitmap.createBitmap(ORIWIDTH, ORIHEIGHT, Config.ARGB_8888);
Canvas c = new Canvas(oriColor);
paint.setShader(lg);
c.drawRect(0, 0, ORIWIDTH, ORIHEIGHT, paint);
paint.setShader(lg2);
c.drawRect(0, 0, ORIWIDTH, ORIHEIGHT, paint);
}
// 右邊的亮度欄
private void drawABar(Canvas c) {
int x, y;
x = (roundColor & 0x00ffffff);
y = (x | 0xff000000);
LinearGradient lg = new LinearGradient(0, 0, layoutWidth, 0, x, y, TileMode.MIRROR);
// 初始化 x = 240 + 6 * 2
y = ORIHEIGHT + (GAP << 2) - GAP + BARHEIGHT;
paint.setColor(0xffffffff);
c.drawBitmap(aBk, 0, y, paint);
paint.setShader(lg);
c.drawRect(0, y, layoutWidth, y + BARHEIGHT, paint);
}
觸控相關的處理就不一一貼了。實際畫出來的效果:

測試界面:

調色盤對話框:

換色後的效果:

來看程式碼。ColorPickerDialog 本體負責視窗尺寸與初始色:
package com.xsl.colorpicker;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.WindowManager;
public class ColorPickerDialog extends Dialog {
private final boolean debug = true;
private final String TAG = "ColorPicker";
Context context;
private String title; //標題
private int mInitialColor; //初始顏色
private OnColorChangedListener mListener;
/**
* 初始顏色為黑色
*/
public ColorPickerDialog(Context context, String title,
OnColorChangedListener listener) {
this(context, Color.BLACK, title, listener);
}
public ColorPickerDialog(Context context, int initialColor, String title,
OnColorChangedListener listener) {
super(context);
this.context = context;
mListener = listener;
mInitialColor = initialColor;
this.title = title;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WindowManager manager = getWindow().getWindowManager();
int height = (int) (manager.getDefaultDisplay().getHeight() * 0.38f);
int width = (int) (manager.getDefaultDisplay().getWidth() * 0.5f);
ColorPickerView myView = new ColorPickerView(context, height, width);
setContentView(myView);
setTitle(title);
}
ColorPickerView 的建構子準備了幾支畫筆:色環用 SweepGradient、中心圓用純色、分隔線與黑白漸變塊各自一支:
private class ColorPickerView extends View {
private Paint mPaint; //漸變色環畫筆
private Paint mCenterPaint; //中間圓畫筆
private Paint mLinePaint; //分隔線畫筆
private Paint mRectPaint; //漸變方塊畫筆
private Shader rectShader; //漸變方塊漸變圖像
private float rectLeft; //漸變方塊左 x 座標
private float rectTop; //漸變方塊上 y 座標
private float rectRight; //漸變方塊右 x 座標
private float rectBottom; //漸變方塊下 y 座標
private final int[] mCircleColors; //漸變色環顏色
private final int[] mRectColors; //漸變方塊顏色
private int mHeight; //View 高
private int mWidth; //View 寬
private float r; //色環半徑(paint 中部)
private float centerRadius; //中心圓半徑
private boolean downInCircle = true; //按在漸變環上
private boolean downInRect; //按在漸變方塊上
private boolean highlightCenter; //高亮
private boolean highlightCenterLittle; //微亮
public ColorPickerView(Context context, int height, int width) {
super(context);
this.mHeight = height - 36;
this.mWidth = width;
setMinimumHeight(height - 36);
setMinimumWidth(width);
//漸變色環參數
mCircleColors = new int[] {
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF,
0xFF00FF00, 0xFFFFFF00, 0xFFFF0000
};
Shader s = new SweepGradient(0, 0, mCircleColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(50);
r = width / 2 * 0.7f - mPaint.getStrokeWidth() * 0.5f;
//中心圓參數
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(mInitialColor);
mCenterPaint.setStrokeWidth(5);
centerRadius = (r - mPaint.getStrokeWidth() / 2) * 0.7f;
//邊框參數
mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mLinePaint.setColor(Color.parseColor("#72A1D1"));
mLinePaint.setStrokeWidth(4);
//黑白漸變參數
mRectColors = new int[]{0xFF000000, mCenterPaint.getColor(), 0xFFFFFFFF};
mRectPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mRectPaint.setStrokeWidth(5);
rectLeft = -r - mPaint.getStrokeWidth() * 0.5f;
rectTop = r + mPaint.getStrokeWidth() * 0.5f
+ mLinePaint.getStrokeMiter() * 0.5f + 15;
rectRight = r + mPaint.getStrokeWidth() * 0.5f;
rectBottom = rectTop + 50;
}
onDraw 依序畫中心圓、色環與黑白漸變塊:
@Override
protected void onDraw(Canvas canvas) {
//移動中心
canvas.translate(mWidth / 2, mHeight / 2 - 50);
//畫中心圓
canvas.drawCircle(0, 0, centerRadius, mCenterPaint);
//是否顯示中心圓外的小圓環
if (highlightCenter || highlightCenterLittle) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (highlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else if (highlightCenterLittle) {
mCenterPaint.setAlpha(0x90);
}
canvas.drawCircle(0, 0, centerRadius + mCenterPaint.getStrokeWidth(), mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
//畫色環
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
//畫黑白漸變塊
if (downInCircle) {
mRectColors[1] = mCenterPaint.getColor();
}
rectShader = new LinearGradient(rectLeft, 0, rectRight, 0,
mRectColors, null, Shader.TileMode.MIRROR);
mRectPaint.setShader(rectShader);
canvas.drawRect(rectLeft, rectTop, rectRight, rectBottom, mRectPaint);
float offset = mLinePaint.getStrokeWidth() / 2;
canvas.drawLine(rectLeft - offset, rectTop - offset * 2,
rectLeft - offset, rectBottom + offset * 2, mLinePaint);//左
canvas.drawLine(rectLeft - offset * 2, rectTop - offset,
rectRight + offset * 2, rectTop - offset, mLinePaint);//上
canvas.drawLine(rectRight + offset, rectTop - offset * 2,
rectRight + offset, rectBottom + offset * 2, mLinePaint);//右
canvas.drawLine(rectLeft - offset * 2, rectBottom + offset,
rectRight + offset * 2, rectBottom + offset, mLinePaint);//下
super.onDraw(canvas);
}
觸控邏輯分成三個區域判斷:色環上取角度、漸變塊上取 X 座標、中心圓則作為「確認」:
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - mWidth / 2;
float y = event.getY() - mHeight / 2 + 50;
boolean inCircle = inColorCircle(x, y,
r + mPaint.getStrokeWidth() / 2, r - mPaint.getStrokeWidth() / 2);
boolean inCenter = inCenter(x, y, centerRadius);
boolean inRect = inRect(x, y);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downInCircle = inCircle;
downInRect = inRect;
highlightCenter = inCenter;
case MotionEvent.ACTION_MOVE:
if (downInCircle && inCircle) {
//按在色環內且移動也在色環內
float angle = (float) Math.atan2(y, x);
float unit = (float) (angle / (2 * Math.PI));
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpCircleColor(mCircleColors, unit));
} else if (downInRect && inRect) {
//按在漸變方塊內且移動也在其中
mCenterPaint.setColor(interpRectColor(mRectColors, x));
}
if ((highlightCenter && inCenter)
|| (highlightCenterLittle && inCenter)) {
highlightCenter = true;
highlightCenterLittle = false;
} else if (highlightCenter || highlightCenterLittle) {
highlightCenter = false;
highlightCenterLittle = true;
} else {
highlightCenter = false;
highlightCenterLittle = false;
}
invalidate();
break;
case MotionEvent.ACTION_UP:
if (highlightCenter && inCenter) {
//點擊中心圓即確認
if (mListener != null) {
mListener.colorChanged(mCenterPaint.getColor());
ColorPickerDialog.this.dismiss();
}
}
if (downInCircle) downInCircle = false;
if (downInRect) downInRect = false;
if (highlightCenter) highlightCenter = false;
if (highlightCenterLittle) highlightCenterLittle = false;
invalidate();
break;
}
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(mWidth, mHeight);
}
幾個小工具函式,用圓面積比較來判斷手指是否落在環上或圓心:
/** 座標是否在色環上 */
private boolean inColorCircle(float x, float y, float outRadius, float inRadius) {
double outCircle = Math.PI * outRadius * outRadius;
double inCircle = Math.PI * inRadius * inRadius;
double fingerCircle = Math.PI * (x * x + y * y);
return fingerCircle < outCircle && fingerCircle > inCircle;
}
/** 座標是否在中心圓上 */
private boolean inCenter(float x, float y, float centerRadius) {
double centerCircle = Math.PI * centerRadius * centerRadius;
double fingerCircle = Math.PI * (x * x + y * y);
return fingerCircle < centerCircle;
}
/** 座標是否在漸變塊中 */
private boolean inRect(float x, float y) {
return x <= rectRight && x >= rectLeft
&& y <= rectBottom && y >= rectTop;
}
顏色插值:色環依角度單值取色,漸變塊依 X 座標在兩端色之間線性過渡:
/** 取得圓環上的顏色 */
private int interpCircleColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
float p = unit * (colors.length - 1);
int i = (int) p;
p -= i; // p 是 [0...1) 的小數部分,i 是索引
int c0 = colors[i];
int c1 = colors[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
/** 取得漸變塊上的顏色 */
private int interpRectColor(int colors[], float x) {
int a, r, g, b, c0, c1;
float p;
if (x < 0) {
c0 = colors[0];
c1 = colors[1];
p = (x + rectRight) / rectRight;
} else {
c0 = colors[1];
c1 = colors[2];
p = x / rectRight;
}
a = ave(Color.alpha(c0), Color.alpha(c1), p);
r = ave(Color.red(c0), Color.red(c1), p);
g = ave(Color.green(c0), Color.green(c1), p);
b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private int ave(int s, int d, float p) {
return s + Math.round(p * (d - s));
}
最後是回調介面與幾個 getter/setter:
/** 回調介面 */
public interface OnColorChangedListener {
/**
* 回調函式
* @param color 選中的顏色
*/
void colorChanged(int color);
}
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public int getmInitialColor() { return mInitialColor; }
public void setmInitialColor(int mInitialColor) { this.mInitialColor = mInitialColor; }
public OnColorChangedListener getmListener() { return mListener; }
public void setmListener(OnColorChangedListener mListener) { this.mListener = mListener; }
}
呼叫端就三行:把當前字色當初始色傳進去,選完之後 setTextColor:
package com.xsl.colorpicker;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class PaintDemoActivity extends Activity {
Context context;
private Button btnColorPicker;
private TextView tvText;
private ColorPickerDialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initViews();
}
/** 初始化 UI */
private void initViews() {
btnColorPicker = (Button) findViewById(R.id.button1);
btnColorPicker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = new ColorPickerDialog(context,
tvText.getTextColors().getDefaultColor(),
getResources().getString(R.string.app_name),
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color) {
tvText.setTextColor(color);
}
});
dialog.show();
}
});
tvText = (TextView) findViewById(R.id.tv);
}
}
整套下來的原理其實不難:色相靠 SweepGradient 環取角度、明度靠 LinearGradient 條取 X 軸,兩者相乘就得到最終顏色。想要更精細,還可以加上最近色塊跟手、鎖定灰階軸等小細節。
Android面試題總結之Android基礎(六):布局與View深度解析
本章節聚焦於 Android 基礎,總結了布局方面的常見面試問題。對 Android 開發者而言,基礎面試無非圍繞 UI、網路、資料庫三大面向,本章整理了幾個經典問題,希
Android 啟動白屏或黑屏閃現問題排查與優化
App 啟動時短暫閃現白屏或黑屏,是許多開發者都會遇到的問題。它通常不是 Crash,而是主題背景與啟動時序共同造成的視覺現象。 白屏與黑屏的原因 若 App 主題使用
動手做一張右下角箭頭的 .9 圖片
先認識 .9 圖片 .9 圖片在 App 開發裡用得非常多,主要目的是防止圖片縮放後變形,確保不失真。 最典型的例子就是微信的聊天氣泡:對方訊息長短不一,背景卻始終是同一
Android Animation 學習筆記:Tween 與 Frame 動畫全解
Android SDK 提供了兩種動畫模式: Tween Animation(補間動畫):對場景中的物件持續做圖形變換(平移、縮放、旋轉)來產生動畫效果。 Frame A