package com.zmlxj.customcompass;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ImageView image=findViewById(R.id.iv_image);
/* // 防止出現Immutable bitmap passed to Canvas constructor錯誤
Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(),
R.drawable.compass_bottom).copy(Bitmap.Config.ARGB_8888, true);
Bitmap bitmap2 = ((BitmapDrawable) getResources().getDrawable(
R.drawable.compass_char)).getBitmap();
Bitmap newBitmap = null;
newBitmap = Bitmap.createBitmap(bitmap1);
Canvas canvas = new Canvas(newBitmap);
Paint paint = new Paint();
int w = bitmap1.getWidth();
int h = bitmap1.getHeight();
int w_2 = bitmap2.getWidth();
int h_2 = bitmap2.getHeight();
paint.setColor(Color.GRAY);
paint.setAlpha(125);
canvas.drawRect(0, 0, bitmap1.getWidth(), bitmap1.getHeight(), paint);
paint = new Paint();
canvas.drawBitmap(bitmap2, Math.abs(w - w_2) / 2,
Math.abs(h - h_2) / 2, paint);
canvas.save();
// 存儲新合成的圖檔
canvas.restore();
image.setImageBitmap(newBitmap);*/
Bitmap bitmap1 = ((BitmapDrawable) getResources().getDrawable(
R.drawable.compass_bottom)).getBitmap();
Bitmap bitmap2 = ((BitmapDrawable) getResources().getDrawable(
R.drawable.compass_char)).getBitmap();
Bitmap bitmap3 = ((BitmapDrawable) getResources().getDrawable(
R.drawable.compass_pointer)).getBitmap();
Drawable[] array = new Drawable[3];
array[0] = new BitmapDrawable(bitmap1);
array[1] = new BitmapDrawable(bitmap2);
array[2] = new BitmapDrawable(bitmap3);
LayerDrawable la = new LayerDrawable(array);
// 其中第一個參數為層的索引号,後面的四個參數分别為left、top、right和bottom
la.setLayerInset(0, 0, 0, 0, 0);
la.setLayerInset(1, 20, 20, 20, 20);
int[] all= getImageWidthHeight();
Log.i("擷取的值",all[0]+"_"+all[1]);
la.setLayerInset(2, 40, (all[1]/8), 40, 40);
image.setImageDrawable(la);
}
public int[] getImageWidthHeight(){
BitmapFactory.Options options = new BitmapFactory.Options();
/**
* 最關鍵在此,把options.inJustDecodeBounds = true;
* 這裡再decodeFile(),傳回的bitmap為空,但此時調用options.outHeight時,已經包含了圖檔的高了
*/
options.inJustDecodeBounds = true;
// Bitmap bitmap = BitmapFactory.decodeFile(this.getResources()., options); // 此時傳回的bitmap為null
BitmapFactory.decodeResource(getResources(),R.drawable.compass_bottom,options);
/**
*options.outHeight為原始圖檔的高
*/
return new int[]{options.outWidth,options.outHeight};
}
}