Android ApiDemo 筆記(一)Content與Graphics
一.package com.example.android.apis.content;
1.ReadAsset:從asset目錄裡讀出
2.ResourcesSample:在values的strings.xml裡取得string,
以及在非activity裡取得方法。
Resources res = context.getResources();
CharSequence cs = res.getText(R.string.styled_text);
3.StyledText:在TextView裡直接setText帶有styled的字串<string name="styled_text">Plain, <b>bold</b>, <i>italic</i>, <b><i>bold-italic</i></b></string>
二.package com.example.android.apis.graphics;
1.AlphaBitmap:應用Paint p.setAntiAlias(true);//抗鋸齒,如果沒有呼叫這個方法,寫上去的字不飽滿,不美觀,看地不太清楚
下圖為p.setAntiAlias(false)效果
下圖為p.setAntiAlias(true)效果
1.1 p.setAlpha(0x80);//透明度
1.2 p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));//14例中FingerPaint:手寫板有這個用法
1.3 p.setTextSize(60);//設定字型大小
1.4 p.setTextAlign(Paint.Align.CENTER);//基準線
1.5 InputStream is = context.getResources().openRawResource(//從drawable裡的圖片轉到bitmap
R.drawable.app_sample_code);
mBitmap = BitmapFactory.decodeStream(is);
1.6 mShader = new LinearGradient(0, 0, 100, 70, new int[] { Color.RED,//漸變
Color.GREEN, Color.BLUE }, null, Shader.TileMode.MIRROR);
p.setShader(mShader);
2.AnimateDrawables 把一張照片動起來,類似跑馬燈的效果,有三個類AnimateDrawables ,AnimateDrawable,ProxyDrawable
2.1 Drawable dr = context.getResources().getDrawable(R.drawable.beach);//獲得Drawable
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());//設定圖的邊界,有放大縮小的作用 這是設定為100,100的邊界效果
2.2 Animation an = new TranslateAnimation(0, 100, 0, 200);//從0,0點到100,200移動的動畫
an.setDuration(2000);//持續時間2秒
an.setRepeatCount(-1);//無限迴圈
2.3 public void draw(Canvas canvas) {
Drawable dr = getProxy();
if (dr != null) {
int sc = canvas.save();//
Animation anim = mAnimation;
if (anim != null) {
anim.getTransformation(AnimationUtils.currentAnimationTimeMillis()//動起來
mTransformation);//該方法根據當前間 (currentTime) 和 interpolator,計算當前的變換,在 outTransformation 中返回
canvas.concat(mTransformation.getMatrix());//對canvas應用矩陣變換
}
dr.draw(canvas);
canvas.restoreToCount(sc);
}
}
注意:canvas.save();//canvas.restoreToCount(sc);是正對出現的
假設我們將要對canvas進行了一系列的設定,例如旋轉,變色等,而又不希望在操作完之後讓這些設定影響到後面的繪畫。
就需要在設定前先save,使用完之後再restore;帶count的恢復,是指直接回復到某個狀態
假設我們設定了clip去繪畫一張圖片的一小部分
一般這麼幹
canvas.save();
canvas.setclip
canvas.drawBitmap
canvas.restore();
3. Arcs:
3.1 mPaints[0] = new Paint();
mPaints[0].setAntiAlias(true);
mPaints[0].setStyle(Paint.Style.FILL);
mPaints[0].setColor(0x88FF0000);
mUseCenters[0] = false;
mPaints[1] = new Paint(mPaints[0]);
mPaints[1].setColor(0x8800FF00);
mUseCenters[1] = true;
mPaints[2] = new Paint(mPaints[0]);
mPaints[2].setStyle(Paint.Style.STROKE);
mPaints[2].setStrokeWidth(4);
mPaints[2].setColor(0x880000FF);
mUseCenters[2] = false;
3.2 canvas.drawArc(oval, mStart, mSweep, useCenter, paint); //useCenter為是否畫中心。mStart起始度數,mSweep跨度
4.BitmapDecode:最下面的國旗是GIF動畫
4.1 兩種載入圖片,再轉成bitmap的方法
// now opts.outWidth and opts.outHeight are the dimension of the
// bitmap, even though bm is null
opts.inJustDecodeBounds = false; // this will request the bm
opts.inSampleSize = 4; // scaled down by 4 面試變成1/4大小
bm = BitmapFactory.decodeStream(is, null, opts);
mBitmap = bm;
// decode an image with transparency
is = context.getResources().openRawResource(R.drawable.frog);
mBitmap2 = BitmapFactory.decodeStream(is);
4.2 mBitmap2.getPixels(pixels, 0, w, 0, 0, w, h);//獲得mBitmap2的畫素顏色值,賦值給pixels,第三個引數為一行的畫素數(矩形的寬)
mBitmap3 = Bitmap.createBitmap(pixels, 0, w, w, h,
Bitmap.Config.ARGB_8888);//用上面的pixels顏色陣列建立一個Bitmap
4.3 mDrawable = context.getResources().getDrawable(R.drawable.button);
mDrawable.setBounds(150, 20, 300, 100);//設定button9的面積(只有Drawable才有這個方法)
4.4 canvas.drawBitmap(mBitmap4, 210, 170, null); //Bitmap的畫法
mDrawable.draw(canvas);//Drawable的畫法
4.5 is = context.getResources().openRawResource(R.drawable.animated_gif);//獲得GIF動畫流
mMovie = Movie.decodeStream(is);//把流轉成Movie
//畫Movie動畫
long now = android.os.SystemClock.uptimeMillis();//當前時間
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();//GIF持續時間
if (dur == 0) {
dur = 1000;
}
int relTime = (int) ((now - mMovieStart) % dur);
mMovie.setTime(relTime);
mMovie.draw(canvas, getWidth() - mMovie.width(), getHeight()//畫動畫,引數為X,Y點
- mMovie.height());
invalidate();//重新整理,不停的畫
}
5. BitmapMesh:(沒看)
5.1 mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.beach); //生成Bitmap
6.BitmapPixels:(沒看)
7. CameraPreview:(沒看)內容同SDK開發大全中的7.15例
7.1 // Hide the window title.隱藏標題
requestWindowFeature(Window.FEATURE_NO_TITLE);
8. Clipping:
8.1
//定好樣式
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(6);//畫筆的寬
mPaint.setTextSize(16);
mPaint.setTextAlign(Paint.Align.RIGHT);
canvas.drawLine(0, 0, 100, 100, mPaint);//畫線 畫的線為mPaint指定的寬度
8.2
canvas.save();
canvas.translate(160, 10);
canvas.clipRect(10, 10, 90, 90);
canvas.clipRect(30, 30, 70, 70, Region.Op.DIFFERENCE);
drawScene(canvas);
canvas.restore();
8.3
canvas.save();
canvas.translate(10, 160);
mPath.reset();
canvas.clipPath(mPath); // makes the clip empty
mPath.addCircle(50, 50, 50, Path.Direction.CCW);
canvas.clipPath(mPath, Region.Op.REPLACE);
drawScene(canvas);
canvas.restore();
9. ColorFilters:
9.1
Paint.FontMetrics fm = mPaint.getFontMetrics();//不知道是什麼意思??????
float mPaintTextOffset = (fm.descent + fm.ascent) * 0.5f;
9.2
mColors = new int[] { 0, 0xCC0000FF, 0x880000FF, 0x440000FF, 0xFFCCCCFF,
0xFF8888FF, 0xFF4444FF, };
mModes = new PorterDuff.Mode[] { PorterDuff.Mode.SRC_ATOP,//過濾器的方式
PorterDuff.Mode.MULTIPLY, };
mModeIndex = 0;
filter = new PorterDuffColorFilter(mColors [i], mModes[mModeIndex]);//用mColors [i]和porter-duff mode的顏色建立一個顏色過濾
mDrawable.setColorFilter(filter);
mDrawable.draw(canvas);
10.ColorMatrixTest
private void setContrast(ColorMatrix cm, float contrast) {
float scale = contrast + 1.f;
float translate = (-.5f * scale + .5f) * 255.f;
cm.set(new float[] { scale, 0, 0, 0, translate, 0, scale, 0, 0,
translate, 0, 0, scale, 0, translate, 0, 0, 0, 1, 0 });
}
ColorMatrix cm = new ColorMatrix();
mAngle += 2;
if (mAngle > 180) {
mAngle = 0;
}
float contrast = mAngle / 180.f;
setContrast(cm, contrast);
paint.setColorFilter(new ColorMatrixColorFilter(cm));//設定顏色過濾
canvas.drawBitmap(mBitmap, x + mBitmap.getWidth() + 10, y, paint);
invalidate();
11.Compass指南針:(沒看)
12.CreateBitmap:
12.1 建立顏色陣列(說實話沒看懂)
private static int[] createColors() {
int[] colors = new int[STRIDE * HEIGHT];
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
int r = x * 255 / (WIDTH - 1);
int g = y * 255 / (HEIGHT - 1);
int b = 255 - Math.min(r, g);
int a = Math.max(r, g);
colors[y * STRIDE + x] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
return colors;
}
12.2
private static Bitmap codec(Bitmap src, Bitmap.CompressFormat format,
int quality) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
src.compress(format, quality, os); //壓縮
byte[] array = os.toByteArray();
return BitmapFactory.decodeByteArray(array, 0, array.length);
}
mJPEG[i] = codec(mBitmaps[i], Bitmap.CompressFormat.JPEG, 80);//用JPEG編碼
13.DensityActivity
13.1
1: LinearLayout root = new LinearLayout(this);//設定一個線性佈局root
2: root.setOrientation(LinearLayout.VERTICAL); //方向垂直
3:
4: LinearLayout layout = new LinearLayout(this);//在root佈局內,又建一個layout佈局
5: addBitmapDrawable(layout, R.drawable.logo120dpi, true);//以logo120dpi為View的背景,並把view加下佈局
6:
7:
8: addBitmapDrawable(layout, R.drawable.logo160dpi, true);
9: //addBitmapDrawable(layout, R.drawable.logo240dpi, true);
10: addLabelToRoot(root, "Prescaled bitmap in drawable");//加入一個TextView到root
11: addChildToRoot(root, layout);
12: setContentView(scrollWrap(root));
13:
14: }
15:
16:
1: private void addLabelToRoot(LinearLayout root, String text) {
2: TextView label = new TextView(this);
3: label.setText(text);
4: root.addView(label, new LinearLayout.LayoutParams(
5: LinearLayout.LayoutParams.FILL_PARENT,
6: LinearLayout.LayoutParams.WRAP_CONTENT));
7: }
8:
9: private void addChildToRoot(LinearLayout root, LinearLayout layout) {
10: root.addView(layout, new LinearLayout.LayoutParams(
11: LinearLayout.LayoutParams.FILL_PARENT,
12: LinearLayout.LayoutParams.WRAP_CONTENT));
13: }
14:
15:
16: private Bitmap loadAndPrintDpi(int id, boolean scale) {
17: Bitmap bitmap;
18: if (scale) {
19: bitmap = BitmapFactory.decodeResource(getResources(), id);
20: } else {
21: BitmapFactory.Options opts = new BitmapFactory.Options();
22: opts.inScaled = false;
23: bitmap = BitmapFactory.decodeResource(getResources(), id, opts);
24: }
25: return bitmap;
26: }
27:
28:
//將bitmap為作View的背景,並把view加下佈局
1: private void addBitmapDrawable(LinearLayout layout, int resource,
2: boolean scale) {
3: Bitmap bitmap;
4: bitmap = loadAndPrintDpi(resource, scale);
5:
6: final View view = new View(this);
7: view.setOnClickListener(new View.OnClickListener() {//給當前veiw設定OnOnClickListener
8: @Override
9: public void onClick(View v) {
10: //Toast.makeText(NewViewTest.this,"View onClick" , Toast.LENGTH_LONG).show();
11: }
12: });
13: view.setOnTouchListener(new View.OnTouchListener() {//給當前view設定OnTouchListener
14: @Override
15: public boolean onTouch(View v, MotionEvent event) {
16: Toast.makeText(NewViewTest.this,"x="+event.getX()+" y="+event.getY() , Toast.LENGTH_LONG).show();
17: v.setBackgroundColor(Color.BLUE);
18:
19: return false;
20: }
21: });
22: final BitmapDrawable d = new BitmapDrawable(getResources(), bitmap);
23: if (!scale)
24: d.setTargetDensity(getResources().getDisplayMetrics());
25: view.setBackgroundDrawable(d);
26:
27: view.setLayoutParams(new LinearLayout.LayoutParams(d.getIntrinsicWidth(), d
28: .getIntrinsicHeight()));
29: layout.addView(view);
30: }
31: private View scrollWrap(View view) {
32: ScrollView scroller = new ScrollView(this);
33: scroller.addView(view, new ScrollView.LayoutParams(
34: ScrollView.LayoutParams.FILL_PARENT,
35: ScrollView.LayoutParams.FILL_PARENT));
36: return scroller;
37: }
38:
39:
14. FingerPaint:手寫板
14.1
1: MaskFilter mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f); //浮雕
2:
3: MaskFilter mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);//模糊
4:
14.2
//觸控事件
1: public boolean onTouchEvent(MotionEvent event) {
2: float x = event.getX();
3: float y = event.getY();
4:
5: switch (event.getAction()) {
6: case MotionEvent.ACTION_DOWN:
7: touch_start(x, y);
8: invalidate();
9: break;
10: case MotionEvent.ACTION_MOVE:
11: touch_move(x, y);
12: invalidate();
13: break;
14: case MotionEvent.ACTION_UP:
15: touch_up();
16: invalidate();
17: break;
18: }
19: return true;
20: }
21:
14.3 畫路徑