鴻蒙Java開發模式11:鴻蒙圖片裁剪功能的實現


鴻蒙入門指南,小白速來!從萌新到高手,怎樣快速掌握鴻蒙開發?【課程入口】

目錄:

1. 鴻蒙版圖片裁剪功能效果展示

2.Java代碼實現

3.裁剪工具類實現

4.《鴻蒙Java開發模式》系列文章合集

1. 鴻蒙版圖片裁剪功能,效果如下:

   首頁

鴻蒙Java開發模式11:鴻蒙圖片裁剪功能的實現

 

圖片裁剪區域:

鴻蒙Java開發模式11:鴻蒙圖片裁剪功能的實現

 

裁剪結果:

 

鴻蒙Java開發模式11:鴻蒙圖片裁剪功能的實現

 

2.Java代碼實現如下:

package com.example.javahm9.slice;

import com.example.javahm9.ResourceTable;
import com.example.javahm9.util.CropImage;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.element.ShapeElement;

public class MainAbilitySlice extends AbilitySlice {

    //定義一個圖片
    Component image;
    //定義一個文本
    Text text;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        //獲取圖片對象對應的component
        image = findComponentById(ResourceTable.Id_result_image);

        /*
         * 如果接收的cropFlag為true
         * 處理剪裁后的圖片
         * 否則跳過
         */
        if(intent.getBooleanParam("cropFlag",false)){
            handleCrop(intent);
        }
        /* 自定義--獲取文本對象對應的component
         * 根據intent里面的cropStatus來顯示不同的文本
         * 0表示未接收到數據
         * 1表示剪裁取消
         * 2表示剪裁成功 有數據
         */
        text = (Text) findComponentById(ResourceTable.Id_text);
        if(intent.getIntParam("cropStatus",0) == 0){
            text.setText("歡迎使用");
        }else if(intent.getIntParam("cropStatus",0) == 1){
            text.setText("剪裁取消");
        }else if(intent.getIntParam("cropStatus",0) == 2){
            text.setText("剪裁成功");
        }


        //獲取button對象對應的component
        Button button = (Button) findComponentById(ResourceTable.Id_button);
        // 設置button的屬性及背景
        ShapeElement background = new ShapeElement();
       // background.setRgbColor(new RgbColor(125, 125, 255));
        background.setCornerRadius(25);
       // button.setBackground(background);
        if (button != null) {
            // 綁定點擊事件
            button.setClickedListener(new Component.ClickedListener() {
                public void onClick(Component v) {
                    begincrop();
                }
            });
        }
    }

    public void begincrop(){
        CropImage.activity()
                .setContext(this)
                .setSource(ResourceTable.Media_a9)
                .setBundleName("com.example.javahm9")
                .setAbilityName("com.example.javahm9.MainAbility")
                .setRequset_code(1234)
                .start(super.getAbility(),this);
    }

    //處理剪裁結果
    private void handleCrop(Intent result) {
        int resultImg = result.getIntParam("resultImg",0);
        int result_code = result.getIntParam("result_code" , 0);
        if(resultImg != 0){
            CropImage.handleImage(result_code , image);
            
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}

3.裁剪工具類實現

package com.example.javahm9.util;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.PixelMapHolder;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import ohos.utils.net.Uri;

/**
 * @Author 李欣
 * <p>
 * 此類是一個工具類
 * <p>
 * 此類是面向於用戶的 面向於MainAbilitySlice的
 * <p>
 * 此類提供設置一些參數的功能,提供了頁面跳轉,跳轉到CropImageActivity的方法,有一些屬性暫時用不到。
 */

public final class CropImage {

    //存一個context
    private static Context mContext;

    //圖片資源文件
    private static int msource;

    //裁減結果
    public static final boolean CROPFLAG = true;

    //空的構造器
    private CropImage() {
    }

    //內部類初始化
    public static ActivityBuilder activity() {
        return new ActivityBuilder(null , null , null , 0);
    }

    /**
     * 這個方法對傳進來的 component進行操作
     * 給這個空的component增加圖片 旋轉等等
     * @param result 一個參數用來判斷返回的結果 以及如何處理
     * @param component 對這個component進行操作
     */
    public static void handleImage(int result, Component component) {

        //203表示裁剪成功(203為自定義的數字)
        if (result == 203) {
            //獲得原始位圖
            PixelMap pixelMap = BitmapUtils.getOriginalPixelMap(mContext , msource).get();

            //創建屏幕工具類 獲得屏幕的寬度
            CropWindowHandler windowHandler = new CropWindowHandler(mContext);

            /**
             * 縮放指數 原始的圖片的縮放大小
             * 數值為原始圖片的寬度(pixelMap.getImageInfo().size.width)除以屏幕的寬度(windowHandler.getWindowWidth()) 的倒數
             */
            float ratio = (float) windowHandler.getWindowWidth()/(float) pixelMap.getImageInfo().size.width;

            //獲得裁剪后的位圖
            PixelMap cropped = CropOverlayView.getCroppedPixelMap();
            PixelMapHolder pixelMapHolder = new PixelMapHolder(cropped);

            //創建bitmaputils工具類,獲得位圖相關數據
            BitmapUtils bitmapUtils = new BitmapUtils(mContext, cropped, 400, msource);

            /**
             * 創建畫位圖的方法
             * 獲取到之前的點擊動作數組 這樣就可以獲得到具體最終的圖片的方向
             * 並且依次按照圖片方向進行旋轉
             */
            Component.DrawTask drawTask = new Component.DrawTask() {
                @Override
                public void onDraw(Component component, Canvas canvas) {

                    //獲得行為動作
                    int[] action = CropImageView.getActionResult();
                    //獲得動作數目
                    int actionIndex = CropImageView.getActionIndexResult();
                    //循環執行旋轉、翻轉動作
                    for (int i = 0; i < actionIndex; i++) {
                        if (action[i] == 1) {
                            //rotate圖像
                            canvas.rotate(90, bitmapUtils.getRealPixelMapWidth() / 2 * ratio, bitmapUtils.getRealPixelMapHeight() / 2 * ratio);
                        } else if (action[i] == 2) {
                            //水平翻轉
                            //向下移動高度
                            canvas.translate(bitmapUtils.getRealPixelMapWidth() * ratio, 0);
                            //向y軸負方向縮放一倍
                            canvas.scale(-1f, 1f);
                        } else if (action[i] == 3) {
                            //垂直翻轉
                            //向下移動高度
                            canvas.translate(0, bitmapUtils.getRealPixelMapHeight() * ratio);
                            //向y軸負方向縮放一倍
                            canvas.scale(1f, -1f);
                        }
                    }

                    //按照原來的比例進行縮放
                    canvas.scale(ratio , ratio);
                    //畫圖
                    canvas.drawPixelMapHolder(pixelMapHolder, 200, 230, new Paint());
                }
            };

            //為component增加drawtask方法
            component.addDrawTask(drawTask);
        }
    }

    public static PixelMap getCroppedPixelMap(){
        return CropOverlayView.getCroppedPixelMap();
    }

    public static final class ActivityBuilder {

        //設置圖片的Uri
        private final Uri mSource;

        //需要跳轉回的bundle的名字
        private String bundleName;

        //需要跳轉回的Ability的名字
        private String abilityName;

        //request_code
        private int request_code;

        //初始化 記錄一些信息
        private ActivityBuilder(Uri source , String bundle , String ability , int request) {
            mSource = source;
            bundleName = bundle;
            abilityName = ability;
            request_code = request;
        }

        //返回一個intent
        public Intent getIntent(Context context) {
            return getIntent(context, CropImageActivity.class);
        }

        //返回一個intent 用來實現頁面跳轉
        public Intent getIntent(Context context, Class<?> cls) {
            Intent intent = new Intent();
            intent.setParam("source", msource);
            if(bundleName != null){
                intent.setParam("bundleName" , bundleName);
            }
            if(abilityName != null){
                intent.setParam("abilityName" , abilityName);
            }
            if(request_code != 0){
                intent.setParam("request_code" , request_code);
            }
            return intent;
        }

        //頁面跳轉
        public void start(Ability ability, AbilitySlice abilitySlice) {
            start(ability, abilitySlice, request_code);
        }

        //頁面跳轉
        public void start(Ability ability, AbilitySlice abilitySlice, int requestCode) {
            //給crop添加操作
            AbilitySlice cropImageAbilitySlice = new CropImageActivity();
            abilitySlice.presentForResult(cropImageAbilitySlice, getIntent(ability), requestCode);
        }

        //設置資源圖片,被裁減的圖片的id
        public ActivityBuilder setSource(int source) {
            msource = source;
            return this;
        }

        //設置context
        public ActivityBuilder setContext(Context context) {
            mContext = context;
            return this;
        }

        //設置需要跳轉回的bundle名字
        public ActivityBuilder setBundleName(String s){
            bundleName = s;
            return this;
        }

        //設置需要跳轉回的ability名字
        public ActivityBuilder setAbilityName(String s){
            abilityName = s;
            return this;
        }

        //設置需要跳轉回時的code
        public ActivityBuilder setRequset_code(int i){
            request_code = i;
            return this;
        }

    }


}


package com.example.javahm9.util;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.RectFloat;
import ohos.bundle.AbilityInfo;
import ohos.media.image.PixelMap;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

/**
 * @Author 李欣
 *
 * 此類為裁剪功能實現的主要頁面
 *
 * 此頁面上顯示了一些功能性的button
 * 還有被裁減圖片以及裁剪框
 */

public class CropImageActivity extends AbilitySlice {

    //定義此slice的Dependent布局
    private DependentLayout myLayout = new DependentLayout(this);

    //被裁減圖片
    private Component mPicture;

    //被裁減圖片的位圖
    private PixelMap mPixelMap;

    //位圖工具類
    private BitmapUtils mBitmapUtils;

    //屏幕工具類
    private CropWindowHandler mCropWindowHandler;

    //裁剪框
    private Component mCropBound;

    //裁剪框工具類
    private CropOverlayView mCropOverlayView;

    //圖片資源
    private int mSource;

    //圖片上邊距
    private final int topIndex = 400;

    //圖片工具類
    private CropImageView mCropImageView;

    //裁減結果的矩陣
    public static RectFloat croppedRectFloat;

    //裁減結果的pixelmap
    public static PixelMap croppedPixelMap;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);

        //創建本slice的布局文件
        DependentLayout.LayoutConfig config = new DependentLayout.LayoutConfig(MATCH_PARENT, MATCH_PARENT);

        //設置默認豎屏
        setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
        //設置布局的背景
        myLayout.setLayoutConfig(config);
        ShapeElement element = new ShapeElement();
        element.setRgbColor(new RgbColor(255, 255, 255));
        myLayout.setBackground(element);

        //設置button,image等
        setupViews(intent);

        //加載裁剪框、背景圖片等等
        loadInput();

        //加載布局
        super.setUIContent(myLayout);
    }

    //按鈕和圖片初始化
    private void setupViews(Intent intent) {
        buttonInit(intent);
        imageInit(intent);
    }

    //按鈕初始化
    private void buttonInit(Intent intent) {
        //創建button
        Button cancel = cancelButton(intent);
        Button rotate = rotateButton();
//        Button horfilp = horizontalFilpButton();
//        Button verfilp =  verticalFilpButton();

        Button crop = cropButton(intent);

        //將button添加到布局
        myLayout.addComponent(cancel);
        myLayout.addComponent(rotate);
//        myLayout.addComponent(horfilp);
//        myLayout.addComponent(verfilp);
        myLayout.addComponent(crop);
    }

    //取消按鈕
    private Button cancelButton(Intent intent) {
        //創建取消button
        Button cancel = new Button(this);
        //為button增加布局條件
        DependentLayout.LayoutConfig cancelLayoutConfig = new DependentLayout.LayoutConfig();
        cancelLayoutConfig.setMargins(140, 50, 0, 0);
        cancelLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_TOP);
        cancelLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_LEFT);
        //設置背景顏色
        cancel.setLayoutConfig(cancelLayoutConfig);
        ShapeElement cancelElement = new ShapeElement();
        cancelElement.setRgbColor(new RgbColor(155, 155, 155));
        cancelElement.setCornerRadius(25);
        cancel.setBackground(cancelElement);
        //設置文本
        cancel.setText("取消");
        cancel.setTextSize(55);
        cancel.setHeight(180);
        cancel.setWidth(220);
        //綁定點擊方法
        cancel.setClickedListener(new Component.ClickedListener() {
            public void onClick(Component v) {
                //為按鈕綁定方法
                cancel(intent);
            }
        });

        return cancel;
    }

    //旋轉按鈕
    private Button rotateButton() {
        //創建旋轉button
        Button rotate = new Button(this);
        //為button增加布局條件
        DependentLayout.LayoutConfig rotateLayoutConfig = new DependentLayout.LayoutConfig();
        rotateLayoutConfig.setMargins(500, 50, 0, 0);
        rotateLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_TOP);
        rotateLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_LEFT);
        rotate.setLayoutConfig(rotateLayoutConfig);
        //設置背景顏色
        ShapeElement rotateElement = new ShapeElement();
        rotateElement.setRgbColor(new RgbColor(255, 228, 181));
        rotateElement.setCornerRadius(25);
        rotate.setBackground(rotateElement);
        //設置文本
        rotate.setText("旋轉");
        rotate.setTextSize(55);
        rotate.setHeight(180);
        rotate.setWidth(220);
        //綁定點擊方法
        rotate.setClickedListener(new Component.ClickedListener() {
            public void onClick(Component v) {
                rotate();
            }
        });

        return rotate;
    }

    //水平翻轉按鈕
    private Button horizontalFilpButton() {
        //創建翻轉button
        Button filp = new Button(this);
        //為button增加布局條件
        DependentLayout.LayoutConfig filpLayoutConfig = new DependentLayout.LayoutConfig();
        filpLayoutConfig.setMargins(0, 50, 300, 0);
        filpLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_TOP);
        filpLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_RIGHT);
        //設置背景顏色
        filp.setLayoutConfig(filpLayoutConfig);
        ShapeElement filpElement = new ShapeElement();
        filpElement.setRgbColor(new RgbColor(180, 238, 180));
        filpElement.setCornerRadius(25);
        filp.setBackground(filpElement);
        //設置文本
        filp.setText("horFilp");
        filp.setTextSize(40);
        filp.setHeight(85);
        filp.setWidth(220);
        //綁定點擊方法
        filp.setClickedListener(new Component.ClickedListener() {
            public void onClick(Component v) {
                horizontalFlip();
            }
        });

        return filp;
    }

    //垂直翻轉按鈕
    private Button verticalFilpButton() {
        //創建翻轉button
        Button filp = new Button(this);
        //為button增加布局條件
        DependentLayout.LayoutConfig filpLayoutConfig = new DependentLayout.LayoutConfig();
        filpLayoutConfig.setMargins(0, 145, 300, 0);
        filpLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_TOP);
        filpLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_RIGHT);
        //設置背景顏色
        filp.setLayoutConfig(filpLayoutConfig);
        ShapeElement filpElement = new ShapeElement();
        filpElement.setRgbColor(new RgbColor(180, 238, 180));
        filpElement.setCornerRadius(25);
        filp.setBackground(filpElement);
        //設置文本
        filp.setText("verFilp");
        filp.setTextSize(40);
        filp.setHeight(85);
        filp.setWidth(220);
        //綁定點擊方法
        filp.setClickedListener(new Component.ClickedListener() {
            public void onClick(Component v) {
                verticalFlip();
            }
        });

        return filp;
    }

    //裁剪按鈕
    private Button cropButton(Intent intent) {
        //創建裁剪button
        Button crop = new Button(this);
        //為button增加布局條件
        DependentLayout.LayoutConfig cropLayoutConfig = new DependentLayout.LayoutConfig();
        cropLayoutConfig.setMargins(820, 50, 0, 0);
        cropLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_TOP);
        cropLayoutConfig.addRule(DependentLayout.LayoutConfig.ALIGN_PARENT_LEFT);
        //設置背景顏色
        crop.setLayoutConfig(cropLayoutConfig);
        ShapeElement cropElement = new ShapeElement();
        cropElement.setRgbColor(new RgbColor(0, 125, 155));
        cropElement.setCornerRadius(25);
        crop.setBackground(cropElement);
        //設置文本
        crop.setText("裁剪");
        crop.setTextSize(55);
        crop.setHeight(180);
        crop.setWidth(220);
        //綁定點擊方法
        crop.setClickedListener(new Component.ClickedListener() {
            public void onClick(Component v) {
                crop(intent);
            }
        });

        return crop;
    }

    //圖片初始化
    private void imageInit(Intent intent) {

        //獲得圖片的id
        int source = intent.getIntParam("source", 0);
        mSource = source;

        //根據圖片id獲取pixelmap
        PixelMap pixelMapOriginal = BitmapUtils.getOriginalPixelMap(this, mSource).get();
        mPixelMap = pixelMapOriginal;

        //創建bitmaputils工具類,獲得位圖相關數據
        BitmapUtils bitmapUtils = new BitmapUtils(this , mPixelMap ,topIndex , mSource );

        //創建cropwindowhandler工具類,獲得windows相關數據
        CropWindowHandler cropWindowHandler = new CropWindowHandler(this);

        //創建圖片工具類,用來獲得圖片
        mCropImageView = new CropImageView(mPixelMap , this ,  mSource , topIndex);

        //獲取展示圖片的component
        mPicture = mCropImageView.getmPicture();

        //計算圖片的位置,使得圖片居中顯示,計算出圖片距離屏幕左邊的空白
        int margin = cropWindowHandler.getWindowWidth()/2 - bitmapUtils.getPixelMapWidth()/2;

        //給mPicture增加布局
        DependentLayout.LayoutConfig componentLayoutConfig = new DependentLayout.LayoutConfig();
        componentLayoutConfig.setMargins(0, topIndex, 0, 0);//邊距
        mPicture.setLayoutConfig(componentLayoutConfig);

        //將圖片加入布局
        myLayout.addComponent(mPicture);

    }

    //初始化工具類,加載裁剪框等等
    private void loadInput() {

        //創建位圖工具類
        mBitmapUtils = new BitmapUtils(this, mPixelMap, 400, mSource);

        //創建屏幕工具類
        mCropWindowHandler = new CropWindowHandler(this);

        //創建裁剪框的工具類
        mCropOverlayView = new CropOverlayView(this, mBitmapUtils, mCropWindowHandler);

        //獲得裁剪框
        mCropBound = mCropOverlayView.getmCropBound();

        //將裁剪框加入布局文件
        myLayout.addComponent(mCropBound);
    }

    //取消裁剪方法
    private void cancel(Intent intentOriginal) {
        Intent intent = new Intent();

        //增加裁剪狀態及結果
        intent.setParam("cropFlag", !CropImage.CROPFLAG);
        intent.setParam("cropStatus", 1);

        // 通過Intent中的OperationBuilder類構造operation對象,指定設備標識(空串表示當前設備)、應用包名、Ability名稱
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(intentOriginal.getStringParam("bundleName"))
                .withAbilityName(intentOriginal.getStringParam("abilityName"))
                .build();
        // 把operation設置到intent中
        intent.setOperation(operation);

        //跳轉
        startAbility(intent);
    }

    //圖片旋轉的方法
    private void rotate(){
        //圖片旋轉
        mCropImageView.rotateOnce();
        //裁剪框旋轉
        mCropOverlayView.rotateOnce();
    }

    //圖片水平翻轉的方法
    private void horizontalFlip(){
        //圖片翻轉
        mCropImageView.horizontalFilp();
        //裁剪框翻轉
        mCropOverlayView.horizontalFilpOnce();
    }

    //圖片垂直翻轉的方法
    private void verticalFlip(){
        mCropImageView.verticalFilp();
        //裁剪框翻轉
        mCropOverlayView.verticalFilpOnce();
    }

    //成功裁剪方法
    private void crop(Intent intentOriginal) {

        //計算裁減后的pixelmap並存放於cropoverlayview中
        mCropOverlayView.croppedPixel(this);

        //顯示到MainActivity
        Intent intent = new Intent();

        //增加裁剪狀態及結果
        intent.setParam("cropFlag", CropImage.CROPFLAG);
        intent.setParam("cropStatus", 2);
        intent.setParam("result_code" , 203);

        RectFloat cropRect = mCropOverlayView.getmCropRect();
        //塞入裁剪結果
        intent.setParam("resultImg", mSource);
        croppedRectFloat = mCropOverlayView.getmCropRect();
        croppedPixelMap = mPixelMap;

        // 通過Intent中的OperationBuilder類構造operation對象,指定設備標識(空串表示當前設備)、應用包名、Ability名稱
        Operation operation = new Intent.OperationBuilder()
                .withDeviceId("")
                .withBundleName(intentOriginal.getStringParam("bundleName"))
                .withAbilityName(intentOriginal.getStringParam("abilityName"))
                .build();
        // 把operation設置到intent中
        intent.setOperation(operation);

        //跳轉
        startAbility(intent);

    }

    @Override
    protected void onStop() {
        super.onStop();
    }
}

作者:六合李欣

想了解更多內容,請訪問: 51CTO和華為官方戰略合作共建的鴻蒙技術社區https://harmonyos.51cto.com


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM