Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 小功能整理

小功能整理

編輯:關於Android編程

一.intent相關

發送短信

        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT,"I am a boy");
        startActivity(intent);

打開相冊

        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivity(intent);

打開浏覽器

        Intent intent=new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        Uri uri=Uri.parse("www.baidu.com");
        intent.setData(uri);
        startActivity(intent);

打電話

    //進入撥號頁面(不需要CALL_PHONE權限)
    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + 10086));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

    //用intent啟動撥打電話,直接撥打(需要CALL_PHONE權限)
    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + 10086));
    startActivity(intent);

安裝apk

    // 新的APK的文件名  
    String str = "newUpdate.apk";  
    // 新APK在存儲卡上的位置  
    String fileName = Environment.getExternalStorageDirectory() + str;  
    // 通過啟動一個Intent讓系統來幫你安裝新的APK  
    Intent intent = new Intent(Intent.ACTION_VIEW);  
    intent.setDataAndType(Uri.fromFile(new File(fileName)),                        "application/vnd.android.package-archive");  
    startActivity(intent); 

打開系統日歷

public static void calendar(Context context) {
        try {
            Intent i = new Intent();
            ComponentName cn = null;
            if (Integer.parseInt(Build.VERSION.SDK) >= 8) {
                cn = new ComponentName("com.android.calendar",
                        "com.android.calendar.LaunchActivity");

            } else {
                cn = new ComponentName("com.google.android.calendar",
                        "com.android.calendar.LaunchActivity");
            }
            i.setComponent(cn);
            context.startActivity(i);
        } catch (ActivityNotFoundException e) {
            // TODO: handle exception
            Logg.e("ActivityNotFoundException", e.toString());
        }
    }

顯示應用選擇器

    Intent cIntent = new Intent(Intent.ACTION_VIEW);
    Intent chooser = Intent.createChooser(cIntent, "選擇打開方式");
    startActivity(chooser);

確認是否存在接收意向的應用

    Intent mIntent = new Intent();
    ComponentName mComp = new ComponentName("com.juxin.jfcc", "com.juxin.jfcc.activity.login.RegisterActivity");//注意AcitivityName(目標應用程序)要完整的,帶包名的PackageName的
    mIntent.setComponent(mComp);
    PackageManager packageManager = getPackageManager();
    List activities = packageManager.queryIntentActivities(mIntent,
    PackageManager.MATCH_DEFAULT_ONLY);
    boolean isIntentSafe = activities.size() > 0;
    showBigToast(activities.size() + "==");

打開其他應用的activity

    // android:exported="true"所要調整的activity必須有這個屬性
    try {
        Intent mIntent = new Intent();
        ComponentName mComp = new ComponentName("com.juxin.jfcc", "com.juxin.jfcc.activity.login.RegisterActivity");//注意AcitivityName(目標應用程序)要完整的,帶包名的PackageName的
        mIntent.setComponent(mComp);
        startActivity(mIntent);
    } catch (Exception e) {
        showBigToast("未找到可用應用程序!");
    }

意圖過濾

mimeType : 類別

提供另外一種表征處理意向的Activity的方法,通常與用戶手勢或Activity開始的位置有關。 系統支持多種不同的類別,但大多數都很少使用。 ?但是,所有隱含意向默認使用 CATEGORY_DEFAULT 進行定義。

用元素在意向過濾器中指定此內容。

android:mimeType 屬性聲明您的Activity處理的數據類型,比如 text/plain 或 image/jpeg。


    
        
        
        
        
    

二.跟View相關

將布局文件保存成圖片文件

/**
* 將布局文件保存成圖片文件
*/
public static void saveLayout2File(View view, final SaveFileListener saveFileListener) {
     handler = new Handler(Looper.getMainLooper());
     final Bitmap bmp = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
     view.draw(new Canvas(bmp));

     File dir = new File(imagePath);
     if (!dir.exists()) {
         dir.mkdirs();
     }

     final String photoUrl = imagePath + System.currentTimeMillis() + ".png";//換成自己的圖片保存路徑
     final File file = new File(photoUrl);

     new Thread() {
        @Override
        public void run() {
            try {
                final boolean bitMapOk = bmp.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (saveFileListener != null) {
                             saveFileListener.onSaveFile(bitMapOk, photoUrl);
                        }
                    }
                });
            } catch (FileNotFoundException e) {
                 e.printStackTrace();
            }
        }
    }.start();
}

三.SD卡相關

SD卡是否存在

    /**
     * @return SD卡是否存在
     */
    public static boolean existSDCard() {
        return (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED));
    }

SD卡容量信息

    /**
     * 單位類型
     */
    public interface Unit {
        int BYTE = 0, KBYTE = 1, MBYTE = 2;
    }

    /**
     * @param unit 單位類型:0:Byte,1:KB,other:MB
     * @return SD卡剩余空間
     */
    public static long getSDFreeSize(int unit) {
        //取得SD卡文件路徑
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //獲取單個數據塊的大小(Byte)
        long blockSize = sf.getBlockSize();
        //空閒的數據塊的數量
        long freeBlocks = sf.getAvailableBlocks();
        //返回SD卡空閒大小
        if (unit == 0) {
            return freeBlocks * blockSize;  //單位Byte
        } else if (unit == 1) {
            return (freeBlocks * blockSize) / 1024;   //單位KB
        } else {
            return (freeBlocks * blockSize) / 1024 / 1024; //單位MB
        }
    }

    /**
     * @return SD卡總容量
     */
    public static long getSDAllSize() {
        //取得SD卡文件路徑
        File path = Environment.getExternalStorageDirectory();
        StatFs sf = new StatFs(path.getPath());
        //獲取單個數據塊的大小(Byte)
        long blockSize = sf.getBlockSize();
        //獲取所有數據塊數
        long allBlocks = sf.getBlockCount();
        //返回SD卡大小
        //return allBlocks * blockSize; //單位Byte
        //return (allBlocks * blockSize)/1024; //單位KB
        return (allBlocks * blockSize) / 1024 / 1024; //單位MB
    }

四.Bitmap相關

圖像的放大縮小方法

    /**
     * 圖像的放大縮小方法
     *
     * @param src    源位圖對象
     * @param scaleX 寬度比例系數
     * @param scaleY 高度比例系數
     * @return 返回位圖對象
     */
    public static Bitmap zoomBitmap(Bitmap src, float scaleX, float scaleY) {
        Matrix matrix = new Matrix();
        matrix.setScale(scaleX, scaleY);
        return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
    }

圖像放大縮小--根據寬度和高度

    /**
     * 圖像放大縮小--根據寬度和高度
     *
     * @param src
     * @param width
     * @param height
     * @return
     */
    public static Bitmap zoomBimtap(Bitmap src, int width, int height) {
        return Bitmap.createScaledBitmap(src, width, height, true);
    }

Bitmap轉byte[]

    /**
     * Bitmap轉byte[]
     *
     * @param bitmap
     * @return
     */
    public static byte[] bitmapToByte(Bitmap bitmap) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
        return out.toByteArray();
    }

byte[]轉Bitmap

    /**
     * byte[]轉Bitmap
     *
     * @param data
     * @return
     */
    public static Bitmap byteToBitmap(byte[] data) {
        if (data.length != 0) {
            return BitmapFactory.decodeByteArray(data, 0, data.length);
        }
        return null;
    }

繪制帶圓角的圖像

    /**
     * 繪制帶圓角的圖像
     *
     * @param src
     * @param radius
     * @return
     */
    public static Bitmap createRoundedCornerBitmap(Bitmap src, int radius) {
        final int w = src.getWidth();
        final int h = src.getHeight();
        // 高清量32位圖
        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bitmap);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(0xff424242);
        // 防止邊緣的鋸齒
        paint.setFilterBitmap(true);
        Rect rect = new Rect(0, 0, w, h);
        RectF rectf = new RectF(rect);
        // 繪制帶圓角的矩形
        canvas.drawRoundRect(rectf, radius, radius, paint);

        // 取兩層繪制交集,顯示上層
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // 繪制圖像
        canvas.drawBitmap(src, rect, rect, paint);
        return bitmap;
    }

創建選中帶提示圖片

    /**
     * 創建選中帶提示圖片
     *
     * @param context
     * @param srcId
     * @param tipId
     * @return
     */
    public static Drawable createSelectedTip(Context context, int srcId, int tipId) {
        Bitmap src = BitmapFactory.decodeResource(context.getResources(), srcId);
        Bitmap tip = BitmapFactory.decodeResource(context.getResources(), tipId);
        final int w = src.getWidth();
        final int h = src.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Paint paint = new Paint();
        Canvas canvas = new Canvas(bitmap);
        //繪制原圖
        canvas.drawBitmap(src, 0, 0, paint);
        //繪制提示圖片
        canvas.drawBitmap(tip, (w - tip.getWidth()), 0, paint);
        return bitmapToDrawable(bitmap);
    }

帶倒影的圖像

    /**
     * 帶倒影的圖像
     *
     * @param src
     * @return
     */
    public static Bitmap createReflectionBitmap(Bitmap src) {
        // 兩個圖像間的空隙
        final int spacing = 4;
        final int w = src.getWidth();
        final int h = src.getHeight();
        // 繪制高質量32位圖
        Bitmap bitmap = Bitmap.createBitmap(w, h + h / 2 + spacing, Config.ARGB_8888);
        // 創建燕X軸的倒影圖像
        Matrix m = new Matrix();
        m.setScale(1, -1);
        Bitmap t_bitmap = Bitmap.createBitmap(src, 0, h / 2, w, h / 2, m, true);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        //  繪制原圖像
        canvas.drawBitmap(src, 0, 0, paint);
        // 繪制倒影圖像
        canvas.drawBitmap(t_bitmap, 0, h + spacing, paint);
        // 線性渲染-沿Y軸高到低渲染
        Shader shader = new LinearGradient(0, h + spacing, 0, h + spacing + h / 2, 0x70ffffff, 0x00ffffff, Shader.TileMode.MIRROR);
        paint.setShader(shader);
        // 取兩層繪制交集,顯示下層。
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        // 繪制渲染倒影的矩形
        canvas.drawRect(0, h + spacing, w, h + h / 2 + spacing, paint);
        return bitmap;
    }

獨立的倒影圖像

    /**
     * 獨立的倒影圖像
     *
     * @param src
     * @return
     */
    public static Bitmap createReflectionBitmapForSingle(Bitmap src) {
        final int w = src.getWidth();
        final int h = src.getHeight();
        // 繪制高質量32位圖
        Bitmap bitmap = Bitmap.createBitmap(w, h / 2, Config.ARGB_8888);
        // 創建沿X軸的倒影圖像
        Matrix m = new Matrix();
        m.setScale(1, -1);
        Bitmap t_bitmap = Bitmap.createBitmap(src, 0, h / 2, w, h / 2, m, true);

        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        // 繪制倒影圖像
        canvas.drawBitmap(t_bitmap, 0, 0, paint);
        // 線性渲染-沿Y軸高到低渲染
        Shader shader = new LinearGradient(0, 0, 0, h / 2, 0x70ffffff,
                0x00ffffff, Shader.TileMode.MIRROR);
        paint.setShader(shader);
        // 取兩層繪制交集。顯示下層。
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
        // 繪制渲染倒影的矩形
        canvas.drawRect(0, 0, w, h / 2, paint);
        return bitmap;
    }

灰色圖像

/**
*灰色圖像
*/
public static Bitmap createGreyBitmap(Bitmap src) {
        final int w = src.getWidth();
        final int h = src.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint = new Paint();
        // 顏色變換的矩陣
        ColorMatrix matrix = new ColorMatrix();
        // saturation 飽和度值,最小可設為0,此時對應的是灰度圖;為1表示飽和度不變,設置大於1,就顯示過飽和
        matrix.setSaturation(0);
        ColorMatrixColorFilter filter = new ColorMatrixColorFilter(matrix);
        paint.setColorFilter(filter);
        canvas.drawBitmap(src, 0, 0, paint);
        return bitmap;
    }

保存圖片

    /**
     * 保存圖片
     *
     * @param src
     * @param filepath
     * @param format:[Bitmap.CompressFormat.PNG,Bitmap.CompressFormat.JPEG]
     * @return
     */
    public static boolean saveImage(Bitmap src, String filepath, CompressFormat format) {
        boolean rs = false;
        File file = new File(filepath);
        try {
            FileOutputStream out = new FileOutputStream(file);
            if (src.compress(format, 100, out)) {
                out.flush();    //寫入流
            }
            out.close();
            rs = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }

添加水印效果

    /**
     * 添加水印效果
     *
     * @param src       源位圖
     * @param watermark 水印
     * @param direction 方向
     * @param spacing   間距
     * @return
     */
    public static Bitmap createWatermark(Bitmap src, Bitmap watermark, int direction, int spacing) {
        final int w = src.getWidth();
        final int h = src.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        canvas.drawBitmap(src, 0, 0, null);
        if (direction == LEFT_TOP) {
            canvas.drawBitmap(watermark, spacing, spacing, null);
        } else if (direction == LEFT_BOTTOM) {
            canvas.drawBitmap(watermark, spacing, h - watermark.getHeight() - spacing, null);
        } else if (direction == RIGHT_TOP) {
            canvas.drawBitmap(watermark, w - watermark.getWidth() - spacing, spacing, null);
        } else if (direction == RIGHT_BOTTOM) {
            canvas.drawBitmap(watermark, w - watermark.getWidth() - spacing, h - watermark.getHeight() - spacing, null);
        }
        return bitmap;
    }

合成圖像

     /**
     * 合成圖像
     *
     * @param direction
     * @param bitmaps
     * @return
     */
    public static Bitmap composeBitmap(int direction, Bitmap... bitmaps) {
        if (bitmaps.length < 2) {
            return null;
        }
        Bitmap firstBitmap = bitmaps[0];
        for (Bitmap bitmap : bitmaps) {
            firstBitmap = composeBitmap(firstBitmap, bitmap, direction);
        }
        return firstBitmap;
    }

    /**
     * 合成兩張圖像
     *
     * @param firstBitmap
     * @param secondBitmap
     * @param direction
     * @return
     */
    private static Bitmap composeBitmap(Bitmap firstBitmap, Bitmap secondBitmap,
                                        int direction) {
        if (firstBitmap == null) {
            return null;
        }
        if (secondBitmap == null) {
            return firstBitmap;
        }
        final int fw = firstBitmap.getWidth();
        final int fh = firstBitmap.getHeight();
        final int sw = secondBitmap.getWidth();
        final int sh = secondBitmap.getHeight();
        Bitmap bitmap = null;
        Canvas canvas = null;
        if (direction == TOP) {
            bitmap = Bitmap.createBitmap(sw > fw ? sw : fw, fh + sh, Config.ARGB_8888);
            canvas = new Canvas(bitmap);
            canvas.drawBitmap(secondBitmap, 0, 0, null);
            canvas.drawBitmap(firstBitmap, 0, sh, null);
        } else if (direction == BOTTOM) {
            bitmap = Bitmap.createBitmap(fw > sw ? fw : sw, fh + sh, Config.ARGB_8888);
            canvas = new Canvas(bitmap);
            canvas.drawBitmap(firstBitmap, 0, 0, null);
            canvas.drawBitmap(secondBitmap, 0, fh, null);
        } else if (direction == LEFT) {
            bitmap = Bitmap.createBitmap(fw + sw, sh > fh ? sh : fh, Config.ARGB_8888);
            canvas = new Canvas(bitmap);
            canvas.drawBitmap(secondBitmap, 0, 0, null);
            canvas.drawBitmap(firstBitmap, sw, 0, null);
        } else if (direction == RIGHT) {
            bitmap = Bitmap.createBitmap(fw + sw, fh > sh ? fh : sh,
                    Config.ARGB_8888);
            canvas = new Canvas(bitmap);
            canvas.drawBitmap(firstBitmap, 0, 0, null);
            canvas.drawBitmap(secondBitmap, fw, 0, null);
        }
        return bitmap;
    }

簡單的截圖(View獲取bitmap,保存文件)

    /**
     * 簡單的截圖(View獲取bitmap,保存文件)
     *
     * @param view     需要轉成圖片的View
     * @param filePath 存儲路徑
     * @return 返回生成的bitmap
     */
    public static Bitmap screenShot(View view, String filePath) {
        long start = System.currentTimeMillis();
        // 獲取屏幕
        view.setDrawingCacheEnabled(true);//開啟cache
        view.buildDrawingCache();
        Bitmap bmp = view.getDrawingCache();
        Logg.i("===========bmp============" + bmp);
        if (bmp != null) {
            try {
                // 圖片文件路徑
                filePath = TextUtils.isEmpty(filePath) ? FilePath.imagePath + File.separator + System.currentTimeMillis() + "screenshot.png" : filePath;
                File fileF = new File(FilePath.imagePath);
                if (!fileF.exists()) {
                    fileF.mkdirs();
                }
                File file = new File(filePath);
                FileOutputStream os = new FileOutputStream(file);
                bmp.compress(Bitmap.CompressFormat.PNG, 100, os);
                os.flush();
                os.close();
            } catch (Exception e) {
            }
        }
        long end = System.currentTimeMillis();
        Logg.i("===========截圖需要的時間============" + (end - start));
        return bmp;
    }

五.工具類

調用文件選擇軟件來選擇文件

    /**
     * 調用文件選擇軟件來選擇文件
     **/
    public static void showFileChooser(Activity activity, int requestCode, String name) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(name + "/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            activity.startActivityForResult(Intent.createChooser(intent, "請選擇一個要上傳的文件"),
                    requestCode);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(activity, "請安裝文件管理器", Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /**
     * 調用文件選擇軟件來選擇文件
     **/
    public static void showForderChooser(Activity activity, int requestCode) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("forder/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        try {
            activity.startActivityForResult(Intent.createChooser(intent, "請選擇一個要上傳的文件"),
                    requestCode);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(activity, "請安裝文件管理器", Toast.LENGTH_SHORT)
                    .show();
        }
    }

MD5處理字符串

/**
 * MD5處理字符串
 */
public class MD5 {
    public static String md5(String string) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10) hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }
}

檢查網絡是否開啟

    /**
     * 檢查網絡是否開啟
     */
    public static boolean isNetworkAvailable(Context context) {
        // 獲得網絡系統連接服務
        ConnectivityManager manager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        return !(networkinfo == null || !networkinfo.isAvailable());
    }

二維碼生成工具類

/**
 * 二維碼生成工具類
 */
public class QRCodeUtil {
    private static Handler handler;

    /**
     * 生成二維碼Bitmap
     *
     * @param content   內容
     * @param widthPix  圖片寬度
     * @param heightPix 圖片高度
     * @param logoBm    二維碼中心的Logo圖標(可以為null)
     * @param filePath  用於存儲二維碼圖片的文件路徑
     * @return 生成二維碼及保存文件是否成功
     */
    public static boolean createQRImage(String content, int widthPix, int heightPix, Bitmap logoBm, String filePath) {
        try {
            if (content == null || "".equals(content)) {
                return false;
            }

            //配置參數
            Map hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            //容錯級別
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            //設置空白邊距的寬度
            hints.put(EncodeHintType.MARGIN, 1); //default is 4

            // 圖像數據轉換,使用了矩陣轉換
            BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, widthPix, heightPix, hints);
            int[] pixels = new int[widthPix * heightPix];
            // 下面這裡按照二維碼的算法,逐個生成二維碼的圖片,
            // 兩個for循環是圖片橫列掃描的結果
            for (int y = 0; y < heightPix; y++) {
                for (int x = 0; x < widthPix; x++) {
                    if (bitMatrix.get(x, y)) {
                        pixels[y * widthPix + x] = 0xff000000;
                    } else {
                        pixels[y * widthPix + x] = 0xffffffff;
                    }
                }
            }

            // 生成二維碼圖片的格式,使用ARGB_8888
            Bitmap bitmap = Bitmap.createBitmap(widthPix, heightPix, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, widthPix, 0, 0, widthPix, heightPix);

            if (logoBm != null) {
                bitmap = addLogo(bitmap, logoBm);
            }

            //必須使用compress方法將bitmap保存到文件中再進行讀取。直接返回的bitmap是沒有任何壓縮的,內存消耗巨大!
            return bitmap != null && bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(filePath));
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 在二維碼中間添加Logo圖案
     */
    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //獲取圖片的寬高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小為二維碼整體大小的1/7
        float scaleFactor = srcWidth * 1.0f / 7 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save(Canvas.ALL_SAVE_FLAG);
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

    public interface QRCodeListener {
        void onQRCode(boolean isSuccess, Bitmap qrBitmap, String filePath);
    }

    private static boolean success = false;

    public static void createQRcode(Context context, String filePath, final String text, final Bitmap logoBm, final QRCodeListener qrCodeListener) {
        handler = new Handler(Looper.getMainLooper());
        if (TextUtils.isEmpty(filePath)) {
            filePath = FilePath.imagePath
                    + "qr_" + MyApplication.userId + ".jpg";
        }
        final String path = filePath;
        //二維碼圖片較大時,生成圖片、保存文件的時間可能較長,因此放在新線程中
        new Thread(new Runnable() {
            @Override
            public void run() {
                success = QRCodeUtil.createQRImage(text, 800, 800, logoBm, path);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (qrCodeListener != null) {
                            qrCodeListener.onQRCode(success, BitmapFactory.decodeFile(path), path);
                        }
                    }
                });
            }
        }).start();
    }

    public static void createQRcode(Context context, String filePath, String text, int logoResId, QRCodeListener qrCodeListener) {
        File file = new File(filePath);
        if (file.exists()) {
            if (qrCodeListener != null) {
                qrCodeListener.onQRCode(true, BitmapFactory.decodeFile(filePath), filePath);
            }
        } else {
            createQRcode(context, filePath, text, BitmapFactory.decodeResource(context.getResources(), logoResId), qrCodeListener);
        }
    }
}
/**
     * dip轉換px
     */
    public static int dip2px(Context context, int dip) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }

    /**
     * px轉換dip
     */
    public static int px2dip(Context context,int px) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (px / scale + 0.5f);
    }

    /**
     * 從主線程looper裡面移除runnable
     */
    public static void removeCallbacks(Runnable runnable) {
        getHandler().removeCallbacks(runnable);
    }

獲取狀態欄高度

    /**
     * 獲取狀態欄高度
     */
public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

通知父容器,占用的寬,高;

    /**
     * 通知父容器,占用的寬,高;
     *
     * @param child
     */
    public static void measureView(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(lpHeight,
                    View.MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }

取圖片上的顏色

private void getBitmapColor() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.background_menu_head);
        //取圖片上的顏色
        Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() {
            @Override
            public void onGenerated(Palette palette) {
                Palette.Swatch swatch = palette.getVibrantSwatch(); //充滿活力的色板
                if (swatch != null) {
                    int rgb = swatch.getRgb();
                    int titleTextColor = swatch.getTitleTextColor();
                    int bodyTextColor = swatch.getBodyTextColor();
                    //HSL色彩模式
                    // hsl[0] is Hue [0 .. 360)色相
                    //hsl[1] is Saturation [0...1]飽和度
                    //hsl[2] is Lightness [0...1]明度
                    float[] hsl = swatch.getHsl();
                    colorBurn(rgb);
                    colorBurn(titleTextColor);
                    colorBurn(bodyTextColor);
                    Logg.d(hsl[0] + "==" + hsl[1] + "==" + hsl[2]);
                }
            }
        });
    }

    private int colorBurn(int RGBValues) {
        int alpha = RGBValues >> 24;
        int red = RGBValues >> 16 & 0xFF;
        int green = RGBValues >> 8 & 0xFF;
        int blue = RGBValues & 0xFF;
        Logg.d(alpha + "==" + red + "==" + green + "==" + blue);
        return Color.rgb(red, green, blue);
    }
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved