diff --git a/README.md b/README.md index 54b0d93b33df274d8fd484cd3747ef97fbf118cf..ac67224271cb2eb0ce0ff443a724cd85728ba9a5 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # ImageSelector **本项目基于开源项目ImageSelector -进行OpenHarmony化的移植和开发,可以通过项目标签以及github地址( https://github.com/donkingliang/ImageSelector )追踪到原安卓项目版本** +进行OpenHarmony化的移植和开发,可以通过项目标签以及github地址( https://github.com/donkingliang/ImageSelector )追踪到原项目版本** #### 项目介绍 - 项目名称:ImageSelector @@ -115,7 +115,7 @@ CloudTest代码测试无异常 火绒安全病毒安全检测通过 -当前版本demo功能与安卓原组件基本无差异 +当前版本demo功能与原组件基本无差异 测试员:杨辉 diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbility.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbility.java index 495d2c9b6bd2b91f6658b17fa8c7836cac592e90..509f1aa8dcb512394cbc4c8c27735d1e95e2f9b8 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbility.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbility.java @@ -15,7 +15,6 @@ package com.flask.colorpicker.cameralibrary; -import com.flask.colorpicker.cameralibrary.listener.PermissionInterface; import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; import ohos.security.SystemPermission; @@ -35,8 +34,7 @@ public class CameraAbility extends Ability { */ public static final int REQ_PERMISSION_CODE = 1003; - private PermissionInterface mPermissionListener; - private List mPermissions = + private final List mPermissions = new LinkedList<>( Arrays.asList( SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE)); @@ -52,19 +50,10 @@ public class CameraAbility extends Ability { mPermissions.removeIf(perM -> verifySelfPermission(perM) == PERMISSION_GRANTED || !canRequestPermission(perM)); if (!mPermissions.isEmpty()) { requestPermissionsFromUser( - mPermissions.toArray(new String[mPermissions.size()]), CameraAbility.REQ_PERMISSION_CODE); + mPermissions.toArray(new String[0]), CameraAbility.REQ_PERMISSION_CODE); } } - /** - * set Permission Listener - * - * @param permissionListener PermissionInterface - */ - public void setPermissionListener(PermissionInterface permissionListener) { - this.mPermissionListener = permissionListener; - } - @Override public void onRequestPermissionsFromUserResult(int requestCode, String[] ss, int[] grantResults) { super.onRequestPermissionsFromUserResult(requestCode, ss, grantResults); diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbilitySlice.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbilitySlice.java index 83dc8c3ef49b704b3501674c25c0e2a255bb158d..f184da2a1a1fa8127f6fcc8a26a0d5f8cc5b636a 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbilitySlice.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraAbilitySlice.java @@ -15,15 +15,12 @@ package com.flask.colorpicker.cameralibrary; -import com.flask.colorpicker.cameralibrary.listener.JCameraListener; import com.flask.colorpicker.cameralibrary.util.LogUtil; import com.flask.colorpicker.cameralibrary.util.ResUtils; import com.flask.colorpicker.cameralibrary.listener.PermissionInterface; -import ohos.aafwk.ability.Ability; import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.agp.components.Component; -import ohos.media.image.PixelMap; import ohos.security.SystemPermission; import java.io.File; @@ -38,8 +35,7 @@ import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; */ public class CameraAbilitySlice extends AbilitySlice implements PermissionInterface { private JCameraView mJCameraView; - private boolean isHavePermission; - private List mPermissions = + private final List mPermissions = new LinkedList<>( Arrays.asList( SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE)); @@ -48,11 +44,6 @@ public class CameraAbilitySlice extends AbilitySlice implements PermissionInterf public void onStart(Intent intent) { super.onStart(intent); super.setUIContent(ResourceTable.Layout_ability_camera); - - Ability ability = getAbility(); - if (ability instanceof CameraAbility) { - ((CameraAbility) ability).setPermissionListener(this); - } getWindow().setTransparent(true); Component component = findComponentById(ResourceTable.Id_jcameraview); if (component instanceof JCameraView) { @@ -65,19 +56,11 @@ public class CameraAbilitySlice extends AbilitySlice implements PermissionInterf mJCameraView.setErrorListener( (errorString, type) -> LogUtil.error(LogUtil.DEFAULT_TAG, "errorString:" + errorString)); mJCameraView.setJCameraListener( - new JCameraListener() { - @Override - public void captureSuccess(PixelMap bitmap, String url) { - Intent fileIntent = new Intent(); - fileIntent.setParam("extra_result_items", url); - getAbility().setResult(1001, fileIntent); - terminate(); - } - - @Override - public void recordSuccess(String url) { - LogUtil.error(LogUtil.DEFAULT_TAG, "recordSuccess"); - } + (bitmap, url) -> { + Intent fileIntent = new Intent(); + fileIntent.setParam("extra_result_items", url); + getAbility().setResult(1001, fileIntent); + terminate(); }); mJCameraView.setLeftClickListener( () -> { @@ -91,13 +74,9 @@ public class CameraAbilitySlice extends AbilitySlice implements PermissionInterf private void reqPermissions() { mPermissions.removeIf(perS -> verifySelfPermission(perS) == PERMISSION_GRANTED || !canRequestPermission(perS)); - if (mPermissions.isEmpty()) { - isHavePermission = true; - } } private void handCamera() { - isHavePermission = false; LogUtil.error(LogUtil.DEFAULT_TAG, "handCamera"); if (mJCameraView != null) { mJCameraView.onResume(); @@ -111,12 +90,6 @@ public class CameraAbilitySlice extends AbilitySlice implements PermissionInterf setResult(new Intent()); } - @Override - public void onReqFinish() { - isHavePermission = true; - handCamera(); - } - @Override public void onActive() { super.onActive(); diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraInterface.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraInterface.java index 930deb1632b31e1bef971b70c86fc8ed43b61f81..cb199787148c6a7a436b539a7f88290c35870a9d 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraInterface.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CameraInterface.java @@ -7,46 +7,28 @@ import com.flask.colorpicker.cameralibrary.listener.CameraStateCallbackImpl; import com.flask.colorpicker.cameralibrary.listener.ErrorListener; import com.flask.colorpicker.cameralibrary.state.CameraMachine; -import com.flask.colorpicker.cameralibrary.util.CameraParamUtil; import com.flask.colorpicker.cameralibrary.util.LogUtil; -import com.flask.colorpicker.cameralibrary.util.DeviceUtil; -import com.flask.colorpicker.cameralibrary.util.FileUtil; -import com.flask.colorpicker.cameralibrary.util.ScreenUtils; import com.flask.colorpicker.cameralibrary.util.AngleUtil; import ohos.agp.animation.AnimatorGroup; import ohos.agp.animation.AnimatorProperty; import ohos.agp.components.Image; -import ohos.agp.graphics.Surface; import ohos.agp.graphics.SurfaceOps; -import ohos.agp.utils.Rect; -import ohos.agp.utils.RectFloat; -import ohos.app.Context; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; import ohos.media.camera.CameraKit; import ohos.media.camera.device.FrameConfig; import ohos.media.camera.device.Camera; -import ohos.media.camera.device.CameraConfig; import ohos.media.camera.device.CameraInfo; -import ohos.media.common.AudioProperty; -import ohos.media.common.Source; -import ohos.media.common.StorageProperty; -import ohos.media.common.VideoProperty; import ohos.media.image.ImageReceiver; -import ohos.media.image.common.ImageFormat; -import ohos.media.image.common.Size; -import ohos.media.recorder.Recorder; import ohos.sensor.agent.CategoryMotionAgent; import ohos.sensor.bean.CategoryMotion; import ohos.sensor.data.CategoryMotionData; import ohos.sensor.listener.ICategoryMotionDataCallback; import java.io.File; -import java.io.IOException; -import java.util.List; /** * Camera Interface @@ -68,41 +50,28 @@ public class CameraInterface { private static volatile CameraInterface sCameraInterface; - private EventHandler mCameraHandler = new EventHandler(EventRunner.create("CameraThread")); - - // 视频质量 - private int mMediaQuality = JCameraView.MEDIA_QUALITY_MIDDLE; + private final EventHandler mCameraHandler = new EventHandler(EventRunner.create("CameraThread")); private CameraKit mCameraKit; - private String mCameraId; private CameraStateCallbackImpl mCameraStateCallback; private FrameConfig.Builder mParams; - private boolean isPreviewing = false; - private int SELECTED_CAMERA = -1; + private int SELECTED_CAMERA; private int CAMERA_BACK_POSITION = 0; private int CAMERA_FRONT_POSITION = 1; - + private boolean isPreviewing = false; private float mScreenProp = -1.0f; - private boolean isRecorder = false; - private Recorder mMediaRecorder; - private String mVideoFileName; - private String mSaveVideoPath; - private String mVideoFileAbsPath; - private ErrorListener mErrorListener; private Image mSwitchView; private Image mFlashLamp; private int mAngle = 0; - private int mCameraAngle = 90; // 摄像头角度 默认为90度 private int mRotation = 0; private int mNowScaleRate = 0; - private int mRecordScaleRate = 0; private CategoryMotionAgent mSm = null; @@ -122,31 +91,7 @@ public class CameraInterface { return sCameraInterface; } - /** - * set SwitchView - * - * @param switchView Image - * @param mFlashLamp Image - */ - public void setSwitchView(Image switchView, Image mFlashLamp) { - this.mSwitchView = switchView; - this.mFlashLamp = mFlashLamp; - if (switchView != null && mCameraStateCallback != null && mCameraStateCallback.getCamera() != null) { - FrameConfig.Builder builder = - mCameraStateCallback.getCamera().getFrameConfigBuilder(Camera.FrameConfigType.FRAME_CONFIG_PREVIEW); - if (builder != null) { - int or = builder.getImageRotation(); - mCameraAngle = - CameraParamUtil.getInstance() - .getCameraDisplayOrientation( - mSwitchView.getContext(), - mCameraId == null ? 0 : Integer.parseInt(mCameraId), - or); - } - } - } - - private ICategoryMotionDataCallback sensorEventListener = + private final ICategoryMotionDataCallback sensorEventListener = new ICategoryMotionDataCallback() { @Override public void onSensorDataModified(CategoryMotionData event) { @@ -182,7 +127,6 @@ public class CameraInterface { int[] rotations = new int[2]; switch (mRotation) { case 0: - rotations[0] = 0; switch (mAngle) { case 90: rotations[1] = -90; @@ -196,7 +140,6 @@ public class CameraInterface { rotations[0] = -90; switch (mAngle) { case 0: - rotations[1] = 0; break; case 180: rotations[1] = -180; @@ -218,7 +161,6 @@ public class CameraInterface { rotations[0] = 90; switch (mAngle) { case 0: - rotations[1] = 0; break; case 180: rotations[1] = 180; @@ -246,7 +188,6 @@ public class CameraInterface { } void setSaveVideoPath(String saveVideoPath) { - this.mSaveVideoPath = saveVideoPath; File file = new File(saveVideoPath); if (!file.exists()) { boolean isSuccess = file.mkdirs(); @@ -274,24 +215,8 @@ public class CameraInterface { switch (type) { case TYPE_RECORDER: // 如果不是录制视频中,上滑不会缩放 - if (!isRecorder) { - return; - } - if (zoom >= 0) { - // 每移动50个像素缩放一个级别 - int scaleRate = (int) (zoom / 40); - if (scaleRate <= mParams.getZoomValue() - && scaleRate >= mNowScaleRate - && mRecordScaleRate != scaleRate) { - setZoom(scaleRate); - mRecordScaleRate = scaleRate; - } - } - break; + return; case TYPE_CAPTURE: - if (isRecorder) { - return; - } // 每移动50个像素缩放一个级别 int scaleRate = (int) (zoom / 50); if (scaleRate < mParams.getZoomValue()) { @@ -310,10 +235,6 @@ public class CameraInterface { } } - void setMediaQuality(int quality) { - this.mMediaQuality = quality; - } - private void setZoom(float zoom) { LogUtil.error(LogUtil.DEFAULT_TAG, "set zoom:" + zoom); if (mCameraStateCallback == null || mCameraStateCallback.getCamera() == null) { @@ -352,7 +273,6 @@ public class CameraInterface { private CameraInterface() { findAvailableCameras(); SELECTED_CAMERA = CAMERA_BACK_POSITION; - mSaveVideoPath = ""; } /** @@ -420,7 +340,7 @@ public class CameraInterface { return; } boolean isBack = cameraTag == CAMERA_BACK_POSITION; - mCameraId = cameraIds.length > 1 && isBack ? cameraIds[0] : cameraIds[1]; + String mCameraId = cameraIds.length > 1 && isBack ? cameraIds[0] : cameraIds[1]; mCameraKit.createCamera(mCameraId, mCameraStateCallback, mCameraHandler); LogUtil.error(LogUtil.DEFAULT_TAG, "open camera success"); } @@ -451,6 +371,7 @@ public class CameraInterface { */ public void doStartPreview(SurfaceOps holder, float screenProp) { isPreviewing = true; + System.out.println(holder); if (this.mScreenProp < 0) { this.mScreenProp = screenProp; } @@ -528,33 +449,16 @@ public class CameraInterface { } } - private static int clamp(int xx, int min, int max) { - if (xx > max) { - return max; - } - if (xx < min) { - return min; - } - return xx; - } - void setErrorListener(ErrorListener errorListener) { this.mErrorListener = errorListener; } - /** - * Stop Record Callback - */ - public interface StopRecordCallback { - void recordResult(String url); - } - - /** - * Focus Callback - */ - public interface FocusCallback { - void focusSuccess(); - } +// /** +// * Focus Callback +// */ +// public interface FocusCallback { +// void focusSuccess(); +// } void registerSensorManager() { if (mSm == null) { @@ -571,6 +475,7 @@ public class CameraInterface { } void isPreview(boolean res) { + System.out.println(isPreviewing); this.isPreviewing = res; } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureButton.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureButton.java index ae8b18733761b19af7ef00f0ddaf0f122ab54a67..fee0886d5620774a33010ec623e78a844213c3cd 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureButton.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureButton.java @@ -1,77 +1,48 @@ package com.flask.colorpicker.cameralibrary; -import static com.flask.colorpicker.cameralibrary.JCameraView.BUTTON_STATE_ONLY_CAPTURE; import com.flask.colorpicker.cameralibrary.constant.Constants; import com.flask.colorpicker.cameralibrary.listener.CaptureListener; -import com.flask.colorpicker.cameralibrary.util.CheckPermission; -import com.flask.colorpicker.cameralibrary.util.DeviceUtil; import com.flask.colorpicker.cameralibrary.util.ValueAnimator; - -import ohos.agp.animation.Animator; -import ohos.agp.animation.AnimatorGroup; import ohos.agp.components.Component; -import ohos.agp.render.Arc; import ohos.agp.render.Canvas; import ohos.agp.render.Paint; import ohos.agp.utils.Color; -import ohos.agp.utils.RectFloat; import ohos.app.Context; -import ohos.eventhandler.EventHandler; -import ohos.eventhandler.EventRunner; import ohos.multimodalinput.event.TouchEvent; -import ohos.utils.IntervalTimer; -public class CaptureButton extends Component implements Component.DrawTask, Component.TouchEventListener { +import static com.flask.colorpicker.cameralibrary.JCameraView.BUTTON_STATE_ONLY_CAPTURE; + +public class CaptureButton extends Component implements Component.DrawTask, Component.TouchEventListener{ public static final int STATE_IDLE = 0x001; // 空闲状态 public static final int STATE_PRESS = 0x002; // 按下状态 - public static final int STATE_LONG_PRESS = 0x003; // 长按状态 - public static final int STATE_RECORDERING = 0x004; // 录制状态 public static final int STATE_BAN = 0x005; // 禁止状态 - private int mProgress_color = 0xEE16AE16; // 进度条颜色 - private int mOutside_color = 0xEEDCDCDC; // 外圆背景色 - private int mInside_color = 0xFFFFFFFF; // 内圆背景色 - private int mPressState; // 当前按钮状态 - private int mButton_state; // 按钮可执行的功能状态(拍照,录制,两者) - - private EventHandler mHandler; - private float mEvent_Y; // Touch_Event_Down时候记录的Y值 + private final int mButton_state; // 按钮可执行的功能状态(拍照,录制,两者) - private Paint mPaint; - - private float mStrokeWidth; // 进度条宽度 - private int mOutside_add_size; // 长按外圆半径变大的Size - private int mInside_reduce_size; // 长安内圆缩小的Size + private final Paint mPaint; // 中心坐标 - private float mCenter_X; - private float mCenter_Y; + private final float mCenter_X; + private final float mCenter_Y; - private float mButton_radius; // 按钮半径 - private float mButton_outside_radius; // 外圆半径 + private final float mButton_outside_radius; // 外圆半径 private float mButton_inside_radius; // 内圆半径 - private RectFloat mRectF; - private CaptureListener mCaptureListener; // 按钮回调接口 - private boolean isTimeCancel = true; // IntervalTimer 计时器即使cancel了,还会走onFinish() - - public CaptureButton(Context context) { - super(context); - } public CaptureButton(Context context, int size) { super(context); - int buttonSize = size; // 按钮大小 - mButton_radius = size / 2.0f; + // 按钮半径 + float mButton_radius = size / 2.0f; mButton_outside_radius = mButton_radius; mButton_inside_radius = mButton_radius * 0.75f; - mStrokeWidth = size / 15f; - mOutside_add_size = size / 5; - mInside_reduce_size = size / 8; + // 进度条宽度 + // 长按外圆半径变大的Size + int mOutside_add_size = size / 5; + // 长安内圆缩小的Size mPaint = new Paint(); mPaint.setAntiAlias(true); @@ -79,15 +50,9 @@ public class CaptureButton extends Component implements Component.DrawTask, Comp mPressState = STATE_IDLE; // 初始化为空闲状态 mButton_state = BUTTON_STATE_ONLY_CAPTURE; // 初始化按钮为拍照 - mCenter_X = (buttonSize + mOutside_add_size * 2) / 2f; - mCenter_Y = (buttonSize + mOutside_add_size * 2) / 2f; + mCenter_X = (size + mOutside_add_size * 2) / 2f; + mCenter_Y = (size + mOutside_add_size * 2) / 2f; - mRectF = - new RectFloat( - mCenter_X - (mButton_radius + mOutside_add_size - mStrokeWidth / 2), - mCenter_Y - (mButton_radius + mOutside_add_size - mStrokeWidth / 2), - mCenter_X + (mButton_radius + mOutside_add_size - mStrokeWidth / 2), - mCenter_Y + (mButton_radius + mOutside_add_size - mStrokeWidth / 2)); addDrawTask(this); setTouchEventListener(this); } @@ -96,9 +61,13 @@ public class CaptureButton extends Component implements Component.DrawTask, Comp public void onDraw(Component component, Canvas canvas) { mPaint.setStyle(Paint.Style.FILL_STYLE); + // 外圆背景色 + int mOutside_color = 0xEEDCDCDC; mPaint.setColor(new Color(mOutside_color)); // 外圆(半透明灰色) canvas.drawCircle(mCenter_X, mCenter_Y, mButton_outside_radius, mPaint); + // 内圆背景色 + int mInside_color = 0xFFFFFFFF; mPaint.setColor(new Color(mInside_color)); // 内圆(白色) canvas.drawCircle(mCenter_X, mCenter_Y, mButton_inside_radius, mPaint); } @@ -116,7 +85,8 @@ public class CaptureButton extends Component implements Component.DrawTask, Comp break; } - mEvent_Y = event.getPointerPosition(event.getIndex()).getY(); + // Touch_Event_Down时候记录的Y值 + event.getPointerPosition(event.getIndex()).getY(); mPressState = STATE_PRESS; // 修改当前状态为点击按下 break; @@ -129,34 +99,17 @@ public class CaptureButton extends Component implements Component.DrawTask, Comp } return true; } - - private void postDelayed(Runnable runnable) { - if (mHandler == null) { - mHandler = new EventHandler(EventRunner.getMainEventRunner()); - } - mHandler.postTask(runnable, 500); - } - - private void removeCallbacks(Runnable runnable) { - if (mHandler == null) { - return; - } - mHandler.removeTask(runnable); - } - // 当手指松开按钮时候处理的逻辑 private void handlerUnPressByState() { // 根据当前状态处理 - switch (mPressState) { - // 当前是点击按下 - case STATE_PRESS: - if (mCaptureListener != null - && (mButton_state == BUTTON_STATE_ONLY_CAPTURE)) { - startCaptureAnimation(mButton_inside_radius); - } else { - mPressState = STATE_IDLE; - } - break; + // 当前是点击按下 + if (mPressState == STATE_PRESS) { + if (mCaptureListener != null + && (mButton_state == BUTTON_STATE_ONLY_CAPTURE)) { + startCaptureAnimation(mButton_inside_radius); + } else { + mPressState = STATE_IDLE; + } } } @@ -185,93 +138,6 @@ public class CaptureButton extends Component implements Component.DrawTask, Comp insideAnimation.setDuration(100); insideAnimation.start(); } - - // 内外圆动画 - private void startRecordAnimation(float outside_start, float outside_end, float inside_start, float inside_end) { - ValueAnimator outsideAnimation = ValueAnimator.ofFloat(outside_start, outside_end); - ValueAnimator insideAnimation = ValueAnimator.ofFloat(inside_start, inside_end); - // 外圆动画监听 - outsideAnimation.addUpdateListener( - (animation, value) -> { - mButton_outside_radius = (float) value; - invalidate(); - }); - // 内圆动画监听 - - insideAnimation.addUpdateListener( - (animation, value) -> { - mButton_inside_radius = (float) value; - invalidate(); - }); - AnimatorGroup animatorGroup = new AnimatorGroup(); - - Animator[] outA = outsideAnimation.getAnimatorValue(); - Animator[] inA = insideAnimation.getAnimatorValue(); - - animatorGroup.setStateChangedListener( - new Animator.StateChangedListener() { - @Override - public void onStart(Animator animator) { - } - - @Override - public void onStop(Animator animator) { - } - - @Override - public void onCancel(Animator animator) { - } - - @Override - public void onEnd(Animator animator) { - onAnimationEnd(); - } - - @Override - public void onPause(Animator animator) { - } - - @Override - public void onResume(Animator animator) { - } - }); - animatorGroup.runParallel(DeviceUtil.concat(outA, inA)); - animatorGroup.setDuration(100); - animatorGroup.start(); - } - - private void onAnimationEnd() { - if (mPressState == STATE_LONG_PRESS) { - if (mCaptureListener != null) { - mCaptureListener.recordStart(); - } - isTimeCancel = false; - mPressState = STATE_RECORDERING; - } - } - - // 长按线程 - private class LongPressRunnable implements Runnable { - @Override - public void run() { - mPressState = STATE_LONG_PRESS; // 如果按下后经过500毫秒则会修改当前状态为长按状态 - // 没有录制权限 - if (CheckPermission.getRecordState() != CheckPermission.STATE_SUCCESS) { - mPressState = STATE_IDLE; - if (mCaptureListener != null) { - mCaptureListener.onError("record no permission", Constants.ERROR_TYPE_RECORD); - return; - } - } - // 启动按钮动画,外圆变大,内圆缩小 - startRecordAnimation( - mButton_outside_radius, - mButton_outside_radius + mOutside_add_size, - mButton_inside_radius, - mButton_inside_radius - mInside_reduce_size); - } - } - /** * 设置回调接口 * @@ -281,46 +147,10 @@ public class CaptureButton extends Component implements Component.DrawTask, Comp this.mCaptureListener = captureListener; } - /** - * 设置按钮功能(拍照和录像) - * - * @param state int - */ - public void setButtonFeatures(int state) { - this.mButton_state = state; - } - - /** - * 是否空闲状态 - * - * @return boolean boolean - */ - public boolean isIdle() { - return mPressState == STATE_IDLE; - } - /** * 设置状态 */ public void resetState() { mPressState = STATE_IDLE; } - - /** - * set Button Circle Color - * @param inside_color int - * @param outside_color int - * @param progress_color int - */ - public void setButtonCircleColor(int inside_color, int outside_color, int progress_color) { - if (inside_color > 0) { - this.mInside_color = inside_color; - } - if (outside_color > 0) { - this.mOutside_color = outside_color; - } - if (progress_color > 0) { - this.mProgress_color = progress_color; - } - } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureLayout.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureLayout.java index 4b7d9e2a4e9b78ebe6a7089b483f0cd4ed7caaf8..feffa6484836beaaa21eb7e3d764cf6de9a81a03 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureLayout.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/CaptureLayout.java @@ -2,7 +2,6 @@ package com.flask.colorpicker.cameralibrary; import com.flask.colorpicker.cameralibrary.listener.CaptureListener; import com.flask.colorpicker.cameralibrary.listener.ClickListener; -import com.flask.colorpicker.cameralibrary.listener.ReturnListener; import com.flask.colorpicker.cameralibrary.listener.TypeListener; import com.flask.colorpicker.cameralibrary.util.LogUtil; @@ -24,9 +23,7 @@ import ohos.global.configuration.Configuration; public class CaptureLayout extends StackLayout { private CaptureListener mCaptureListener; // 拍照按钮监听 private TypeListener mTypeListener; // 拍照或录制后接结果按钮监听 - private ReturnListener returnListener; // 退出按钮监听 private ClickListener mLeftClickListener; // 左边按钮监听 - private ClickListener mRightClickListener; // 右边按钮监听 private CaptureButton mBtn_capture; // 拍照按钮 private TypeButton mBtn_confirm; // 确认按钮 @@ -35,14 +32,11 @@ public class CaptureLayout extends StackLayout { private Image mIv_custom_left; // 左边自定义按钮 private Text mTxt_tip; // 提示文本 - private int mLayout_width; - private int mLayout_height; + private final int mLayout_width; - private int mButton_size; + private final int mButton_size; private int mIconLeft = 0; - private int mIconRight = 0; private Element mLeftElement; - private Element mRightElement; private boolean isFirst = true; private boolean isFromEndByRecord = false; @@ -55,20 +49,8 @@ public class CaptureLayout extends StackLayout { this.mCaptureListener = captureListener; } - public void setReturnListener(ReturnListener returnListener) { - this.returnListener = returnListener; - } - - public CaptureLayout(Context context) { - this(context, null); - } - public CaptureLayout(Context context, AttrSet attrs) { - this(context, attrs, null); - } - - public CaptureLayout(Context context, AttrSet attrs, String defStyleAttr) { - super(context, attrs, defStyleAttr); + super(context, attrs, null); DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay(getContext()).get().getAttributes(); int screenWidth = displayAttributes.width; @@ -79,7 +61,6 @@ public class CaptureLayout extends StackLayout { } mButton_size = (int) (mLayout_width / 4.5f); - mLayout_height = mButton_size + (mButton_size / 5) * 2 + 100; initView(); initEvent(); @@ -353,33 +334,9 @@ public class CaptureLayout extends StackLayout { } } - public void setTextWithAnimation(String tip) { - mTxt_tip.setText(tip); - AnimatorProperty animatorTxtTip = new AnimatorProperty(mTxt_tip); - animatorTxtTip.alpha(0f).alpha(1f).alpha(1f).alpha(0f); - animatorTxtTip.setDuration(2500); - animatorTxtTip.start(); - } - - public void setButtonColor(int in_color, int out_color, int progress_color) { - mBtn_capture.setButtonCircleColor(in_color, out_color, progress_color); - } - - public void setButtonFeatures(int state) { - mBtn_capture.setButtonFeatures(state); - } - - public void setTip(String tip) { - mTxt_tip.setText(tip); - } - - public void showTip() { - mTxt_tip.setVisibility(VISIBLE); - } - public void setIconSrc(Element leftElement, Element rightElement) { + System.out.println(rightElement); this.mLeftElement = leftElement; - this.mRightElement = rightElement; if (leftElement != null) { mIv_custom_left.setImageElement(leftElement); mIv_custom_left.setVisibility(VISIBLE); @@ -391,8 +348,8 @@ public class CaptureLayout extends StackLayout { } public void setIconSrc(int iconLeft, int iconRight) { + System.out.println(iconRight); this.mIconLeft = iconLeft; - this.mIconRight = iconRight; if (this.mIconLeft != 0) { mIv_custom_left.setPixelMap(iconLeft); mIv_custom_left.setVisibility(VISIBLE); @@ -408,6 +365,7 @@ public class CaptureLayout extends StackLayout { } public void setRightClickListener(ClickListener rightClickListener) { - this.mRightClickListener = rightClickListener; + System.out.println(rightClickListener); + // 右边按钮监听 } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/FocusView.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/FocusView.java index f18fdac851f05e2c18b87b8e7dafbfb00b1fd2e0..97f92e5eecb2df4ecf99d24dbe2fc205b1167dfb 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/FocusView.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/FocusView.java @@ -12,22 +12,15 @@ import ohos.agp.utils.RectFloat; import ohos.app.Context; public class FocusView extends Component implements Component.DrawTask { - private int mSize; - private int mCenter_x; - private int mCenter_y; - private int mLength; - private Paint mPaint; + private final int mSize; + private final int mCenter_x; + private final int mCenter_y; + private final int mLength; + private final Paint mPaint; - public FocusView(Context context) { - this(context, null); - } public FocusView(Context context, AttrSet attrs) { - this(context, attrs, 0); - } - - public FocusView(Context context, AttrSet attrs, int defStyleAttr) { - super(context, attrs, defStyleAttr); + super(context, attrs, 0); this.mSize = ScreenUtils.getScreenWidth(context) / 3; mPaint = new Paint(); mPaint.setAntiAlias(true); diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/JCameraView.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/JCameraView.java index 13ddcb1023c560951b2bb9c30555759d71f842b1..70e53b602bd27e44a424a0ea7db222761c3f2110 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/JCameraView.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/JCameraView.java @@ -23,9 +23,7 @@ import ohos.agp.components.ComponentContainer; import ohos.agp.components.element.Element; import ohos.agp.components.surfaceprovider.SurfaceProvider; -import ohos.agp.graphics.Surface; import ohos.agp.graphics.SurfaceOps; -import ohos.agp.utils.LayoutAlignment; import ohos.agp.window.service.DisplayAttributes; import ohos.agp.window.service.DisplayManager; import ohos.agp.window.service.WindowManager; @@ -33,9 +31,7 @@ import ohos.app.Context; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; import ohos.global.configuration.Configuration; -import ohos.media.audio.AudioManager; import ohos.media.camera.params.Metadata; -import ohos.media.common.Source; import ohos.media.image.ImageReceiver; import ohos.media.image.PixelMap; import ohos.media.image.common.ImageFormat; @@ -43,7 +39,6 @@ import ohos.media.player.Player; import ohos.multimodalinput.event.TouchEvent; import ohos.utils.net.Uri; -import java.net.URI; import java.util.Optional; public class JCameraView extends StackLayout @@ -59,30 +54,10 @@ public class JCameraView extends StackLayout public static final int TYPE_SHORT = 0x003; public static final int TYPE_DEFAULT = 0x004; - // 录制视频比特率 - public static final int MEDIA_QUALITY_HIGH = 20 * 100000; - public static final int MEDIA_QUALITY_MIDDLE = 16 * 100000; - public static final int MEDIA_QUALITY_LOW = 12 * 100000; - public static final int MEDIA_QUALITY_POOR = 8 * 100000; - public static final int MEDIA_QUALITY_FUNNY = 4 * 100000; - public static final int MEDIA_QUALITY_DESPAIR = 2 * 100000; - public static final int MEDIA_QUALITY_SORRY = 1 * 80000; - public static final int BUTTON_STATE_ONLY_CAPTURE = 0x101; // 只能拍照 - - private static final String TAG = "JCameraView"; - private static final int IMAGE_RCV_CAPACITY = 5; - /** - * 闪关灯状态 - */ - private static final int TYPE_FLASH_AUTO = 0x021; - private static final int TYPE_FLASH_ON = 0x022; - private static final int TYPE_FLASH_OFF = 0x023; - private int type_flash = TYPE_FLASH_OFF; - // Camera状态机 private CameraMachine mMachine; // 回调监听 @@ -90,7 +65,7 @@ public class JCameraView extends StackLayout private ClickListener mLeftClickListener; private ClickListener mRightClickListener; private EventHandler mHandler; - private Context mContext; + private final Context mContext; private StackLayout mVideoView; private Image mPhoto; private Image mSwitchCamera; @@ -102,14 +77,8 @@ public class JCameraView extends StackLayout private float mScreenProp = 0f; private PixelMap mCaptureBitmap; // 捕获的图片 - private String mVideoUrl; // 视频URL - - // 切换摄像头按钮的参数 - private int mIconSrc = 0; // 图标资源 private int mIconLeft = 0; // 左图标 private int mIconRight = 0; // 右图标 - private int mRecordDuration = 0; // 录制时间 - // 缩放梯度 private int mZoomGradient = 0; private float mFirstTouchLength = 0; @@ -121,18 +90,6 @@ public class JCameraView extends StackLayout private boolean isCameraDestroyed = false; private ErrorListener mErrorListener; - /** - * 设置切换摄像头的图标 - * - * @param iconSrc int - */ - public void setIconSrc(int iconSrc) { - this.mIconSrc = iconSrc; - if (mSwitchCamera != null && iconSrc > 0) { - mSwitchCamera.setPixelMap(iconSrc); - } - } - /** * 设置自定义图标 * @@ -159,16 +116,8 @@ public class JCameraView extends StackLayout } } - public JCameraView(Context context) { - this(context, null); - } - public JCameraView(Context context, AttrSet attrs) { - this(context, attrs, ""); - } - - public JCameraView(Context context, AttrSet attrs, String defStyleAttr) { - super(context, attrs, defStyleAttr); + super(context, attrs); mContext = context; if (CheckPermission.checkPermission(mContext)) { initData(); @@ -177,8 +126,6 @@ public class JCameraView extends StackLayout } private void initData() { - FileUtil.initPath(mContext); - mLayout_width = ScreenUtils.getScreenWidth(mContext); float screenHeight = ScreenUtils.getScreenHeight(mContext); @@ -193,7 +140,7 @@ public class JCameraView extends StackLayout // 缩放梯度 mZoomGradient = (int) (mLayout_width / 16f); - mMachine = new CameraMachine(getContext(), this, this); + mMachine = new CameraMachine(getContext(), this); mImageReceiver.setImageArrivalListener(new IImageArrivalListenerImpl(mMachine)); } @@ -343,11 +290,6 @@ public class JCameraView extends StackLayout return mImageReceiver; } - @Override - public Context getAppContext() { - return mContext; - } - private void reInitStatus() { resetState(TYPE_DEFAULT); // 重置状态 CameraInterface.getInstance().registerSensorManager(); @@ -369,7 +311,7 @@ public class JCameraView extends StackLayout LogUtil.info(LogUtil.DEFAULT_TAG, "JCameraView onPause"); stopVideo(); resetState(TYPE_PICTURE); - CameraInterface.getInstance().isPreview(false); + CameraInterface.getInstance().isPreview(true); CameraInterface.getInstance().unregisterSensorManager(); } @@ -447,7 +389,7 @@ public class JCameraView extends StackLayout // 对焦框指示器动画 private void setFocusViewWidthAnimation(float xx, float yy) { - mMachine.focus(xx, yy, () -> mFocusView.setVisibility(HIDE)); + mMachine.focus(xx, yy); } /** @@ -478,24 +420,6 @@ public class JCameraView extends StackLayout CameraInterface.getInstance().setErrorListener(errorListener); } - /** - * 设置CaptureButton功能(拍照和录像) - * - * @param state int - */ - public void setFeatures(int state) { - this.mCaptureLayout.setButtonFeatures(state); - } - - /** - * 设置录制质量 - * - * @param quality int - */ - public void setMediaQuality(int quality) { - CameraInterface.getInstance().setMediaQuality(quality); - } - @Override public void resetState(int type) { if (mVideoView == null) { @@ -504,8 +428,6 @@ public class JCameraView extends StackLayout switch (type) { case TYPE_VIDEO: stopVideo(); // 停止播放 - // 初始化VideoView - FileUtil.deleteFile(mVideoUrl); mVideoView.setLayoutConfig( new StackLayout.LayoutConfig(LayoutConfig.MATCH_PARENT, LayoutConfig.MATCH_PARENT)); mMachine.start(getVideoHolder(), mScreenProp); @@ -532,11 +454,10 @@ public class JCameraView extends StackLayout mPhoto.setVisibility(INVISIBLE); if (mJCameraListener != null) { Uri uri = FileUtil.saveImageToPicture(getContext(),"JCamera", mCaptureBitmap); - mJCameraListener.captureSuccess(mCaptureBitmap,uri.toString()); + mJCameraListener.captureSuccess(mCaptureBitmap,uri+""); } break; case TYPE_SHORT: - break; case TYPE_DEFAULT: break; } @@ -591,14 +512,6 @@ public class JCameraView extends StackLayout return null; } - @Override - public void playVideo(final String url) { - LogUtil.error(LogUtil.DEFAULT_TAG, "playVideo url:" + Uri.parse(url).toString()); - isPlay = true; - initSurface(); - mVideoUrl = url; - } - @Override public void stopVideo() { if (mMediaPlayer != null && mMediaPlayer.isNowPlaying()) { @@ -609,20 +522,9 @@ public class JCameraView extends StackLayout } @Override - public void setTip(String tip) { - mCaptureLayout.setTip(tip); - } - - @Override - public void startPreviewCallback() { - LogUtil.info(LogUtil.DEFAULT_TAG, "startPreviewCallback"); - handlerFoucs(mFocusView.getWidth() / 2f, mFocusView.getHeight() / 2f); - } - - @Override - public boolean handlerFoucs(float pointX, float pointY) { + public void handlerFoucs(float pointX, float pointY) { if (pointY > mCaptureLayout.getTop()) { - return false; + return; } mFocusView.setVisibility(VISIBLE); if (pointX < mFocusView.getWidth() / 2f) { @@ -651,7 +553,6 @@ public class JCameraView extends StackLayout animatorGroup.runParallel(scaleAnimation, alphaAnimation); animatorGroup.setDuration(400); animatorGroup.start(); - return true; } /** @@ -673,19 +574,7 @@ public class JCameraView extends StackLayout } private void setFlashRes() { - switch (type_flash) { - case TYPE_FLASH_AUTO: - mMachine.flash(Metadata.FlashMode.FLASH_AUTO); - break; - case TYPE_FLASH_ON: - mMachine.flash(Metadata.FlashMode.FLASH_OPEN); - break; - case TYPE_FLASH_OFF: - mMachine.flash(Metadata.FlashMode.FLASH_CLOSE); - break; - default: - break; - } + mMachine.flash(Metadata.FlashMode.FLASH_CLOSE); LogUtil.error(LogUtil.DEFAULT_TAG, "setFlashRes end"); } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/TypeButton.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/TypeButton.java index d528aec9ff4f6776dc6dc0729e004d58210ca519..de96d7a4b05466ebefb63d7df8c910ce59a34c22 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/TypeButton.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/TypeButton.java @@ -21,23 +21,19 @@ public class TypeButton extends Component implements Component.DrawTask { * TYPE CONFIRM */ public static final int TYPE_CONFIRM = 0x002; - private int mButton_type; - private int mButton_size; + private final int mButton_type; + private final int mButton_size; - private float mCenter_X; - private float mCenter_Y; - private float mButton_radius; + private final float mCenter_X; + private final float mCenter_Y; + private final float mButton_radius; - private Paint mPaint; - private Path mPath; - private float mStrokeWidth; + private final Paint mPaint; + private final Path mPath; + private final float mStrokeWidth; - private float mIndex; - private RectFloat mRectF; - - public TypeButton(Context context) { - super(context); - } + private final float mIndex; + private final RectFloat mRectF; public TypeButton(Context context, int type, int size) { super(context); diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/constant/Constants.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/constant/Constants.java index e2ea109ac3403c127e3a33dc6597b1caf802d43c..15cbc6625c3c38f7b9b2708f414ce660775cd34e 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/constant/Constants.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/constant/Constants.java @@ -28,15 +28,6 @@ public class Constants { * ERROR TYPE_RECORD */ public static final int ERROR_TYPE_RECORD = 0x00102; - /** - * recorder fps - */ - public static final int RECORDER_FPS = 30; - - /** - * recorder rate - */ - public static final int RECORDER_RATE = 30; private Constants() { } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/CameraStateCallbackImpl.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/CameraStateCallbackImpl.java index 907e95eecffb4dfd733348182e3494ece60ac5b5..89382d551f67648c643ead94de26f3cfb37f71bd 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/CameraStateCallbackImpl.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/CameraStateCallbackImpl.java @@ -23,40 +23,25 @@ import com.flask.colorpicker.cameralibrary.util.LogUtil; import ohos.agp.components.surfaceprovider.SurfaceProvider; import ohos.agp.graphics.Surface; import ohos.agp.graphics.SurfaceOps; -import ohos.eventhandler.EventHandler; -import ohos.eventhandler.EventRunner; - import ohos.media.camera.device.CameraStateCallback; import ohos.media.camera.device.Camera; import ohos.media.camera.device.CameraConfig; import ohos.media.camera.device.FrameConfig; -import ohos.media.recorder.Recorder; - import java.util.Optional; /** * CameraStateCallback Impl */ public class CameraStateCallbackImpl extends CameraStateCallback { - private CameraMachine mMachine; + private final CameraMachine mMachine; private Camera mCamera; - private Recorder mRecorder; public CameraStateCallbackImpl(CameraMachine machine) { this.mMachine = machine; } - /** - * set Recorder - * - * @param recorder Recorder - */ - public void setRecorder(Recorder recorder) { - this.mRecorder = recorder; - } - @Override public void onCreated(Camera camera) { super.onCreated(camera); @@ -108,29 +93,17 @@ public class CameraStateCallbackImpl extends CameraStateCallback { } FrameConfig.Builder framePreviewConfigBuilder = camera.getFrameConfigBuilder(FRAME_CONFIG_PREVIEW); framePreviewConfigBuilder.addSurface(surfaceOps.get().getSurface()); - if (mRecorder != null) { - Surface surface = mRecorder.getVideoSurface(); - framePreviewConfigBuilder.addSurface(surface); - } + FrameConfig config = framePreviewConfigBuilder.build(); try { // 启动循环帧捕获 - int triggerId = camera.triggerLoopingCapture(config); + camera.triggerLoopingCapture(config); } catch (IllegalArgumentException e) { LogUtil.error(LogUtil.DEFAULT_TAG, "onConfigured IllegalArgumentException e:" + e.getMessage()); } catch (IllegalStateException e) { LogUtil.error(LogUtil.DEFAULT_TAG, "onConfigured IllegalStateException e:" + e.getMessage()); } - if (mRecorder != null) { - new EventHandler(EventRunner.getMainEventRunner()) - .postTask( - new Runnable() { - @Override - public void run() { - mRecorder.start(); - } - }); - } + LogUtil.error(LogUtil.DEFAULT_TAG, "onConfigured end"); } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/IImageArrivalListenerImpl.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/IImageArrivalListenerImpl.java index e940ea36e305e82bee94bfc8e24834d280e07c74..9ef782e721602e1c396c0911ba6edbb0559f869a 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/IImageArrivalListenerImpl.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/IImageArrivalListenerImpl.java @@ -31,7 +31,7 @@ import ohos.media.image.common.ImageFormat; * IImageArrivalListener Impl */ public class IImageArrivalListenerImpl implements ImageReceiver.IImageArrivalListener { - private CameraMachine mMachine; + private final CameraMachine mMachine; public IImageArrivalListenerImpl(CameraMachine machine) { this.mMachine = machine; diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/JCameraListener.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/JCameraListener.java index fb38340b49e7e6a1280bced4d417de9caaff1a72..67d629313b1e890f00ce90d45b29f984a71f7316 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/JCameraListener.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/JCameraListener.java @@ -7,6 +7,4 @@ import ohos.media.image.PixelMap; */ public interface JCameraListener { void captureSuccess(PixelMap bitmap,String url); - - void recordSuccess(String url); } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/PermissionInterface.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/PermissionInterface.java index 652d9bb50da21130c4220e3fcdd39f1e0b1a9ae6..79580a7c1a6cfbaa8f1bf163e5c69ce1989d0018 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/PermissionInterface.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/PermissionInterface.java @@ -19,5 +19,4 @@ package com.flask.colorpicker.cameralibrary.listener; * Permission Interface */ public interface PermissionInterface { - void onReqFinish(); } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/ResultListener.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/ResultListener.java deleted file mode 100644 index 3957bcc2e20ff67ec4629d6418e3f31f6657cfd3..0000000000000000000000000000000000000000 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/ResultListener.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.flask.colorpicker.cameralibrary.listener; - -/** - * Result Listener - */ -public interface ResultListener { - void callback(); -} diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/ReturnListener.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/ReturnListener.java index 2f59b9d7079c4df2b27e00e2b2bf3c66f629f627..26f05bf5a45035efe7f04c96b69af9a609fc1aac 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/ReturnListener.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/listener/ReturnListener.java @@ -4,5 +4,4 @@ package com.flask.colorpicker.cameralibrary.listener; * Return Listener */ public interface ReturnListener { - void onReturn(); } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/BorrowPictureState.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/BorrowPictureState.java index 7a092560978b9d3f38886545ff74e14544a35a60..0060508429eb6c09feac8699e474817c5e7b279b 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/BorrowPictureState.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/BorrowPictureState.java @@ -9,7 +9,7 @@ import ohos.agp.graphics.SurfaceOps; * Borrow Picture State */ public class BorrowPictureState implements State { - private CameraMachine mMachine; + private final CameraMachine mMachine; public BorrowPictureState(CameraMachine machine) { this.mMachine = machine; @@ -25,7 +25,7 @@ public class BorrowPictureState implements State { public void stop() {} @Override - public void focus(float x, float y, CameraInterface.FocusCallback callback) {} + public void focus(float x, float y) {} @Override public void switchCamera(SurfaceOps holder, float screenProp) {} diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/BorrowVideoState.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/BorrowVideoState.java deleted file mode 100644 index 3fb37cf4eddcb9a4126575261a0f2aa7ae2c3a7f..0000000000000000000000000000000000000000 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/BorrowVideoState.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.flask.colorpicker.cameralibrary.state; - -import com.flask.colorpicker.cameralibrary.CameraInterface; -import com.flask.colorpicker.cameralibrary.JCameraView; -import com.flask.colorpicker.cameralibrary.util.LogUtil; - -import ohos.agp.graphics.SurfaceOps; - -/** - * Borrow Video State - */ -public class BorrowVideoState implements State { - private CameraMachine mMachine; - - public BorrowVideoState(CameraMachine machine) { - this.mMachine = machine; - } - - @Override - public void start(SurfaceOps holder, float screenProp) { - CameraInterface.getInstance().doStartPreview(holder, screenProp); - mMachine.setState(mMachine.getPreviewState()); - } - - @Override - public void stop() {} - - @Override - public void focus(float x, float y, CameraInterface.FocusCallback callback) {} - - @Override - public void switchCamera(SurfaceOps holder, float screenProp) {} - - @Override - public void restart() {} - - @Override - public void capture() {} - - @Override - public void record() {} - - @Override - public void stopRecord(boolean isShort, long time) {} - - @Override - public void cancel(SurfaceOps holder, float screenProp) { - mMachine.getView().resetState(JCameraView.TYPE_VIDEO); - mMachine.setState(mMachine.getPreviewState()); - } - - @Override - public void confirm() { - mMachine.getView().confirmState(JCameraView.TYPE_VIDEO); - mMachine.setState(mMachine.getPreviewState()); - } - - @Override - public void zoom(float zoom, int type) { - LogUtil.info(LogUtil.DEFAULT_TAG, "set zoom:" + zoom); - } - - @Override - public void flash(int mode) {} -} diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/CameraMachine.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/CameraMachine.java index 797468868775b172608ac513c015020bb998d0ee..67fcc09d40d619a1b9d5505ae0674697fd33a736 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/CameraMachine.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/CameraMachine.java @@ -3,7 +3,6 @@ package com.flask.colorpicker.cameralibrary.state; import com.flask.colorpicker.cameralibrary.CameraInterface; import com.flask.colorpicker.cameralibrary.view.CameraView; -import ohos.agp.graphics.Surface; import ohos.agp.graphics.SurfaceOps; import ohos.app.Context; @@ -11,24 +10,20 @@ import ohos.app.Context; * Camera Machine */ public class CameraMachine implements State { - private Context mContext; + private final Context mContext; private State mState; - private CameraView mView; - private CameraInterface.CameraOpenOverCallback mCameraOpenOverCallback; + private final CameraView mView; - private State mPreviewState; // 浏览状态(空闲) - private State mBorrowPictureState; // 浏览图片 - private State mBorrowVideoState; // 浏览视频 + private final State mPreviewState; // 浏览状态(空闲) + private final State mBorrowPictureState; // 浏览图片 public CameraMachine( - Context context, CameraView view, CameraInterface.CameraOpenOverCallback cameraOpenOverCallback) { + Context context, CameraView view) { this.mContext = context; mPreviewState = new PreviewState(this); mBorrowPictureState = new BorrowPictureState(this); - mBorrowVideoState = new BorrowVideoState(this); // 默认设置为空闲状态 this.mState = mPreviewState; - this.mCameraOpenOverCallback = cameraOpenOverCallback; this.mView = view; } @@ -68,15 +63,6 @@ public class CameraMachine implements State { return mBorrowPictureState; } - /** - * 获取浏览视频状态 - * - * @return State - */ - State getBorrowVideoState() { - return mBorrowVideoState; - } - /** * 获取空闲状态 * @@ -97,8 +83,8 @@ public class CameraMachine implements State { } @Override - public void focus(float xx, float yy, CameraInterface.FocusCallback callback) { - mState.focus(xx, yy, callback); + public void focus(float xx, float yy) { + mState.focus(xx, yy); } @Override diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/PreviewState.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/PreviewState.java index 427d6292ebaf5e7c8f5fce1e3505fd964ad577f5..d82da3e3555e884905575d284714f7b3848bde06 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/PreviewState.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/PreviewState.java @@ -1,14 +1,11 @@ package com.flask.colorpicker.cameralibrary.state; import com.flask.colorpicker.cameralibrary.CameraInterface; -import com.flask.colorpicker.cameralibrary.JCameraView; import com.flask.colorpicker.cameralibrary.util.LogUtil; - -import ohos.agp.graphics.Surface; import ohos.agp.graphics.SurfaceOps; class PreviewState implements State { - private CameraMachine mMachine; + private final CameraMachine mMachine; PreviewState(CameraMachine machine) { this.mMachine = machine; @@ -25,7 +22,7 @@ class PreviewState implements State { } @Override - public void focus(float xx, float yy, CameraInterface.FocusCallback callback) { + public void focus(float xx, float yy) { mMachine.getView().handlerFoucs(xx, yy); } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/State.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/State.java index 22b2b5b011e3ceacaa4279f1dce9881ea5bdf4c2..c3dabc1b08dfda39f86f070098845f6cbce1f795 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/State.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/state/State.java @@ -1,8 +1,6 @@ package com.flask.colorpicker.cameralibrary.state; - import com.flask.colorpicker.cameralibrary.CameraInterface; -import ohos.agp.graphics.Surface; import ohos.agp.graphics.SurfaceOps; /** @@ -13,7 +11,7 @@ public interface State { void stop(); - void focus(float x, float y, CameraInterface.FocusCallback callback); + void focus(float x, float y); void switchCamera(SurfaceOps holder, float screenProp); diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/AngleUtil.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/AngleUtil.java index 8b3579894017a7425c691a3d03dd3542e52b3023..34140aa6ddbd16b5071d154dfe18300601d010b9 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/AngleUtil.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/AngleUtil.java @@ -12,40 +12,19 @@ public class AngleUtil { */ public static int getSensorAngle(float rx, float ry) { if (Math.abs(rx) > Math.abs(ry)) { - /** - * 横屏倾斜角度比较大 - */ if (rx > 4) { - /** - * 左边倾斜 - */ return 270; } else if (rx < -4) { - /** - * 右边倾斜 - */ return 90; } else { - /** - * 倾斜角度不够大 - */ return 0; } } else { if (ry > 7) { - /** - * 左边倾斜 - */ return 0; } else if (ry < -7) { - /** - * 右边倾斜 - */ return 180; } else { - /** - * 倾斜角度不够大 - */ return 0; } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CameraParamUtil.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CameraParamUtil.java index 14d7b241fe2a2fcbe0e1cddbd4db753ab4ba0d4f..83fd427a093eeb0b46903eca83212a897325dc95 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CameraParamUtil.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CameraParamUtil.java @@ -5,11 +5,6 @@ import ohos.agp.window.service.DisplayManager; import ohos.app.Context; import ohos.media.camera.CameraKit; import ohos.media.camera.device.CameraInfo; -import ohos.media.image.common.Size; - -import java.util.Collections; -import java.util.Comparator; -import java.util.List; /** * CameraParam Util @@ -37,8 +32,6 @@ public class CameraParamUtil { private static CameraParamUtil sCameraParamUtil = null; - private CameraSizeComparator sizeComparator = new CameraSizeComparator(); - private CameraParamUtil() { } @@ -51,137 +44,8 @@ public class CameraParamUtil { public static CameraParamUtil getInstance() { if (sCameraParamUtil == null) { sCameraParamUtil = new CameraParamUtil(); - return sCameraParamUtil; - } else { - return sCameraParamUtil; - } - } - - /** - * get PreviewSize - * - * @param list List - * @param th int - * @param rate float - * @return Size - */ - public Size getPreviewSize(List list, int th, float rate) { - int i = 0; - for (Size size : list) { - if ((size.width > th) && equalRate(size, rate)) { - LogUtil.info(LogUtil.DEFAULT_TAG, "MakeSure Preview :w = " + size.width + - " h = " + size.height); - break; - } - i++; - } - if (i == list.size()) { - return getBestSize(list, rate); - } else { - return list.get(i); - } - } - - /** - * get Picture Size - * - * @param list List - * @param th int - * @param rate float - * @return Size - */ - public Size getPictureSize(List list, int th, float rate) { - Collections.sort(list, sizeComparator); - int i = 0; - for (Size size : list) { - if ((size.width > th) && equalRate(size, rate)) { - LogUtil.info(LogUtil.DEFAULT_TAG, "MakeSure Picture :w = " + size.width + - " h = " + size.height); - break; - } - i++; - } - if (i == list.size()) { - return getBestSize(list, rate); - } else { - return list.get(i); - } - } - - private Size getBestSize(List list, float rate) { - float previewDisparity = 100; - int index = 0; - for (int i = 0; i < list.size(); i++) { - Size cur = list.get(i); - float prop = (float) cur.width / (float) cur.height; - if (Math.abs(rate - prop) < previewDisparity) { - previewDisparity = Math.abs(rate - prop); - index = i; - } - } - return list.get(index); - } - - private boolean equalRate(Size ss, float rate) { - float rr = (float) (ss.width) / (float) (ss.height); - return Math.abs(rr - rate) <= 0.2; - } - - /** - * Supported FocusMode - * - * @param focusList List - * @param focusMode String - * @return boolean - */ - public boolean isSupportedFocusMode(List focusList, String focusMode) { - for (int i = 0; i < focusList.size(); i++) { - if (focusMode.equals(focusList.get(i))) { - LogUtil.info(LogUtil.DEFAULT_TAG, "FocusMode supported " + focusMode); - return true; - } - } - return false; - } - - /** - * Supported PictureFormats - * - * @param supportedPictureFormats List - * @param jpeg int - * @return boolean - */ - public boolean isSupportedPictureFormats(List supportedPictureFormats, int jpeg) { - for (int i = 0; i < supportedPictureFormats.size(); i++) { - if (jpeg == supportedPictureFormats.get(i)) { - LogUtil.info(LogUtil.DEFAULT_TAG, "Formats supported " + jpeg); - return true; - } - } - LogUtil.info(LogUtil.DEFAULT_TAG, "Formats not supported " + jpeg); - return false; - } - - /** - * Camera Size Comparator - */ - private static class CameraSizeComparator implements Comparator { - /** - * compare - * - * @param lhs Size - * @param rhs Size - * @return int - */ - public int compare(Size lhs, Size rhs) { - if (lhs.width == rhs.width) { - return 0; - } else if (lhs.width > rhs.width) { - return 1; - } else { - return -1; - } } + return sCameraParamUtil; } /** diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CheckPermission.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CheckPermission.java index b637b7288eb876695744bbfea462c8582d11c197..f0ab1f680fd72af5c26ddac5f9091a35538312b1 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CheckPermission.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/CheckPermission.java @@ -37,7 +37,7 @@ public class CheckPermission { */ public static final int STATE_ERROR = -2; - private static List sPermissions = + private final static List sPermissions = new LinkedList<>( Arrays.asList( SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE)); @@ -72,45 +72,36 @@ public class CheckPermission { } private static int handAudioRecord(int minBuffer, AudioCapturer audioCapturer) { - AudioCapturer audioRecord = audioCapturer; short[] point = new short[minBuffer]; int readSize; try { - audioRecord.start(); // 检测是否可以进入初始化状态 + audioCapturer.start(); // 检测是否可以进入初始化状态 } catch (Exception e) { - if (audioRecord != null) { - audioRecord.release(); - audioRecord = null; + if (audioCapturer != null) { + audioCapturer.release(); } return STATE_NO_PERMISSION; } - if (audioRecord.getState() != AudioCapturer.State.STATE_RECORDING) { + if (audioCapturer.getState() != AudioCapturer.State.STATE_RECORDING) { // 6.0以下机型都会返回此状态,故使用时需要判断bulid版本 // 检测是否在录音中 - if (audioRecord != null) { - audioRecord.stop(); - audioRecord.release(); - audioRecord = null; + if (audioCapturer != null) { + audioCapturer.stop(); + audioCapturer.release(); LogUtil.debug(LogUtil.DEFAULT_TAG, "The recorder is in use"); } return STATE_RECORDING; } else { // 检测是否可以获取录音结果 - readSize = audioRecord.read(point, 0, point.length); + readSize = audioCapturer.read(point, 0, point.length); + if (audioCapturer != null) { + audioCapturer.stop(); + audioCapturer.release(); + } if (readSize <= 0) { - if (audioRecord != null) { - audioRecord.stop(); - audioRecord.release(); - audioRecord = null; - } LogUtil.error(LogUtil.DEFAULT_TAG, "audioRecord result is empty"); return STATE_NO_PERMISSION; } else { - if (audioRecord != null) { - audioRecord.stop(); - audioRecord.release(); - audioRecord = null; - } return STATE_SUCCESS; } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/DeviceUtil.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/DeviceUtil.java index c7941e43a71afe291d592641c6055da7bc80cde7..d8501f4286076a76c3a1c3e427b231b5c867c021 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/DeviceUtil.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/DeviceUtil.java @@ -1,46 +1,11 @@ package com.flask.colorpicker.cameralibrary.util; -import ohos.system.DeviceInfo; - import java.util.Arrays; /** * Device Util */ public class DeviceUtil { - private static String[] sHuaweiRongyao = { - "hwH60", // 荣耀6 - "hwPE", // 荣耀6 plus - "hwH30", // 3c - "hwHol", // 3c畅玩版 - "hwG750", // 3x - "hw7D", // x1 - "hwChe2", // x1 - }; - - /** - * get Device Model - * - * @return String - */ - public static String getDeviceModel() { - return DeviceInfo.getDeviceType(); - } - - /** - * isHuaWei Rongyao - * - * @return boolean - */ - public static boolean isHuaWeiRongyao() { - int length = sHuaweiRongyao.length; - for (int i = 0; i < length; i++) { - if (sHuaweiRongyao[i].equals(getDeviceModel())) { - return true; - } - } - return false; - } /** * 数组合并 diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/FileUtil.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/FileUtil.java index 544b78d7b965faaf61e9b4491062a1d89a038862..a98375814fa22a1ed1a915b75ed32a18a0bf5e5e 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/FileUtil.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/FileUtil.java @@ -3,14 +3,11 @@ package com.flask.colorpicker.cameralibrary.util; import ohos.aafwk.ability.DataAbilityHelper; import ohos.app.Context; import ohos.data.rdb.ValuesBucket; -import ohos.data.usage.DataUsage; -import ohos.data.usage.MountState; import ohos.media.image.ImagePacker; import ohos.media.image.PixelMap; import ohos.media.photokit.metadata.AVStorage; import ohos.utils.net.Uri; -import java.io.BufferedOutputStream; import java.io.File; import java.io.FileDescriptor; import java.io.FileOutputStream; @@ -26,7 +23,7 @@ public class FileUtil { */ public static String sCacheFilePath = ""; - private static String DST_FOLDER_NAME = "JCamera"; + private final static String DST_FOLDER_NAME = "JCamera"; private static File sParentPath; private static String sStoragePath = ""; @@ -34,12 +31,8 @@ public class FileUtil { * file 初始化 * * @param context Context - * @return path */ - public static String initPath(Context context) { - if (context == null) { - throw new RuntimeException("file init,but context is null"); - } + public static void initPath(Context context) { if (sParentPath == null) { sParentPath = getCachePathFile(context); } @@ -57,7 +50,6 @@ public class FileUtil { } } } - return sStoragePath; } /** @@ -74,53 +66,13 @@ public class FileUtil { return context.getCacheDir(); } - /** - * save 圖片到 內存中 - * - * @param dir String - * @param pixelMap PixelMap - * @param context Context - * @return String - */ - public static String saveBitmap(String dir, PixelMap pixelMap, Context context) { - DST_FOLDER_NAME = dir; - String path = initPath(context); - long dataTake = System.currentTimeMillis(); - String jpegName = path + File.separator + "picture_" + dataTake + ".jpg"; - ImagePacker imagePacker = ImagePacker.create(); - boolean isSuccess = false; - FileOutputStream fileOutputStream = null; - try { - fileOutputStream = new FileOutputStream(jpegName); - ImagePacker.PackingOptions options = new ImagePacker.PackingOptions(); - options.quality = 100; - options.format = "image/jpeg"; - imagePacker.initializePacking(fileOutputStream, options); - imagePacker.addImage(pixelMap); - imagePacker.finalizePacking(); - isSuccess = true; - } catch (IOException e) { - LogUtil.error(LogUtil.DEFAULT_TAG, "saveBitmap e:" + e.getMessage()); - } finally { - if (fileOutputStream != null) { - try { - fileOutputStream.close(); - } catch (IOException ex) { - LogUtil.error(LogUtil.DEFAULT_TAG, "ex:" + ex); - } - } - imagePacker.release(); - } - return isSuccess ? jpegName : ""; - } - /** * 存儲圖片到圖庫 * - * @param context - * @param fileName - * @param pixelMap - * @return + * @param context context + * @param fileName fileName + * @param pixelMap pixelMap + * @return 存儲圖片到圖庫 */ public static Uri saveImageToPicture(Context context, String fileName, PixelMap pixelMap) { try { @@ -145,7 +97,7 @@ public class FileUtil { if (result) { result = imagePacker.addImage(pixelMap); if (result) { - long dataSize = imagePacker.finalizePacking(); + imagePacker.finalizePacking(); } } outputStream.flush(); @@ -161,44 +113,18 @@ public class FileUtil { return null; } - /** - * 判断是否是照片 - */ - public static boolean checkIsImageFile(String fName) { - boolean isImageFile = false; - //获取拓展名 - String fileEnd = fName.substring(fName.lastIndexOf(".") + 1, - fName.length()).toLowerCase(); - if (fileEnd.equals("jpg") || fileEnd.equals("png") || fileEnd.equals("gif") - || fileEnd.equals("jpeg") || fileEnd.equals("bmp")) { - isImageFile = true; - } else { - isImageFile = false; - } - return isImageFile; - } - /** * delete File * * @param url String - * @return boolean */ - public static boolean deleteFile(String url) { - boolean result = false; + public static void deleteFile(String url) { File file = new File(url); if (file.exists()) { - result = file.delete(); + boolean ifdelete = file.delete(); + if(ifdelete){ + System.out.println("result"); + } } - return result; - } - - /** - * is ExternalStorage Writable - * - * @return boolean - */ - public static boolean isExternalStorageWritable() { - return DataUsage.getDiskMountedStatus().equals(MountState.DISK_MOUNTED); } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/LogUtil.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/LogUtil.java index 00001da1096f3cf73233c693a195c763691daadd..e85c341fc2de4d2b97396607a9f96e1e296aeb81 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/LogUtil.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/LogUtil.java @@ -16,8 +16,6 @@ public class LogUtil { private static final String SEPARATE_SYMBOL = ":"; - private static final String SEPARATE_COMMA_SYMBOL = ","; - private static final String VERSION_CODE = "100001"; private static final String SEPARATE_SLASH_SYMBOL = "/"; @@ -38,14 +36,12 @@ public class LogUtil { * * @param tag 日志打印类标签 * @param format 标准格式化参数 - * @param msg 日志打印信息 - * @param 信息可以传入任何类型 */ - public static void debug(String tag, String format, T... msg) { + public static void debug(String tag, String format) { if (HiLog.isLoggable(WATCH_DOMAIN, tag, HiLog.INFO)) { - if (!isEmpty(tag)) { + if (isEmpty(tag)) { sCombinedMsg = tag + SEPARATE_SYMBOL + format; - HiLog.debug(LABEL_LOG, sCombinedMsg, msg); + HiLog.debug(LABEL_LOG, sCombinedMsg); } } } @@ -55,29 +51,12 @@ public class LogUtil { * * @param tag 日志打印类标签 * @param format 标准格式化参数 - * @param msg 日志打印信息 - */ - public static void info(String tag, String format, T... msg) { - if (HiLog.isLoggable(WATCH_DOMAIN, tag, HiLog.INFO)) { - if (!isEmpty(tag)) { - sCombinedMsg = tag + SEPARATE_SYMBOL + format; - HiLog.info(LABEL_LOG, sCombinedMsg, msg); - } - } - } - - /** - * warn级别日志打印方法 - * - * @param tag 日志打印类标签 - * @param format 标准格式化参数 - * @param msg 日志打印信息 */ - public static void warn(String tag, String format, T... msg) { + public static void info(String tag, String format) { if (HiLog.isLoggable(WATCH_DOMAIN, tag, HiLog.INFO)) { - if (!isEmpty(tag)) { + if (isEmpty(tag)) { sCombinedMsg = tag + SEPARATE_SYMBOL + format; - HiLog.warn(LABEL_LOG, sCombinedMsg, msg); + HiLog.info(LABEL_LOG, sCombinedMsg); } } } @@ -87,13 +66,12 @@ public class LogUtil { * * @param tag 日志打印类标签 * @param format 标准格式化参数 - * @param msg 日志打印信息 */ - public static void error(String tag, String format, T... msg) { + public static void error(String tag, String format) { if (HiLog.isLoggable(WATCH_DOMAIN, tag, HiLog.INFO)) { - if (!isEmpty(tag)) { + if (isEmpty(tag)) { sCombinedMsg = tag + SEPARATE_SYMBOL + format; - HiLog.error(LABEL_LOG, sCombinedMsg, msg); + HiLog.error(LABEL_LOG, sCombinedMsg); } } } @@ -103,18 +81,17 @@ public class LogUtil { * * @param tag 日志打印类标签 * @param format 标准格式化参数 - * @param msg 日志打印信息 */ - public static void fatal(String tag, String format, T... msg) { + public static void fatal(String tag, String format) { if (HiLog.isLoggable(WATCH_DOMAIN, tag, HiLog.INFO)) { - if (!isEmpty(tag)) { + if (isEmpty(tag)) { sCombinedMsg = tag + SEPARATE_SYMBOL + format; - HiLog.fatal(LABEL_LOG, sCombinedMsg, msg); + HiLog.fatal(LABEL_LOG, sCombinedMsg); } } } private static boolean isEmpty(CharSequence str) { - return str == null || str.length() == 0; + return str != null && str.length() != 0; } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ResUtils.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ResUtils.java index 06f6f98b832e234a55e12262da44805fe1d59334..a48c45064bec615d0782647e2d72a6c356299a4e 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ResUtils.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ResUtils.java @@ -15,26 +15,14 @@ package com.flask.colorpicker.cameralibrary.util; -import ohos.agp.colors.RgbColor; -import ohos.agp.components.element.Element; -import ohos.agp.components.element.PixelMapElement; -import ohos.agp.components.element.ShapeElement; import ohos.agp.components.element.VectorElement; -import ohos.agp.render.Arc; -import ohos.agp.utils.Color; import ohos.app.Context; import ohos.global.resource.ResourceManager; import ohos.global.resource.NotExistException; import ohos.global.resource.WrongTypeException; -import ohos.global.resource.RawFileEntry; -import ohos.global.resource.Resource; - -import ohos.media.image.ImageSource; -import ohos.media.image.PixelMap; import java.io.IOException; -import java.util.Optional; /** * Res Utils @@ -46,125 +34,6 @@ public class ResUtils { LogUtil.info(TAG, "Entering ResUtil()"); } - /** - * get the path from id - * - * @param context the context - * @param id the id - * @return the path from id - */ - public static String getPathById(Context context, int id) { - LogUtil.info(TAG, "Entering getPathById"); - String path = ""; - if (context == null) { - LogUtil.error(TAG, "getPathById -> get null context"); - return path; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtil.error(TAG, "getPathById -> get null ResourceManager"); - return path; - } - try { - path = manager.getMediaPath(id); - } catch (IOException e) { - LogUtil.error(TAG, "getPathById -> IOException"); - } catch (NotExistException e) { - LogUtil.error(TAG, "getPathById -> NotExistException"); - } catch (WrongTypeException e) { - LogUtil.error(TAG, "getPathById -> WrongTypeException"); - } - return path; - } - - /** - * get the new color - * - * @param context the context - * @param id the id - * @return the color - */ - public static Color getNewColor(Context context, int id) { - LogUtil.info(TAG, "Entering getNewColor"); - Color result = new Color(getColor(context, id)); - return result; - } - - /** - * get the color - * - * @param context the context - * @param id the id - * @return the color - */ - public static int getColor(Context context, int id) { - LogUtil.info(TAG, "Entering getColor"); - int result = 0; - if (context == null) { - LogUtil.error(TAG, "getColor -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtil.error(TAG, "getColor -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getColor(); - } catch (IOException e) { - LogUtil.error(TAG, "getColor -> IOException"); - } catch (NotExistException e) { - LogUtil.error(TAG, "getColor -> NotExistException"); - } catch (WrongTypeException e) { - LogUtil.error(TAG, "getColor -> WrongTypeException"); - } - return result; - } - - /** - * get the dimen value - * - * @param context the context - * @param id the id - * @return get the float dimen value - */ - public static float getDimen(Context context, int id) { - LogUtil.info(TAG, "Entering getDimen"); - float result = 0; - if (context == null) { - LogUtil.error(TAG, "getDimen -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtil.error(TAG, "getDimen -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getFloat(); - } catch (IOException e) { - LogUtil.error(TAG, "getDimen -> IOException"); - } catch (NotExistException e) { - LogUtil.error(TAG, "getDimen -> NotExistException"); - } catch (WrongTypeException e) { - LogUtil.error(TAG, "getDimen -> WrongTypeException"); - } - return result; - } - - /** - * get the dimen value - * - * @param context the context - * @param id the id - * @return get the int dimen value - */ - public static int getIntDimen(Context context, int id) { - LogUtil.info(TAG, "Entering getIntDimen"); - float value = getDimen(context, id); - return (int) (value >= 0 ? value + 0.5f : value - 0.5f); - } - /** * get string * @@ -196,99 +65,6 @@ public class ResUtils { return result; } - /** - * get boolean - * - * @param context the context - * @param id the boolean id - * @return boolean of the given id - */ - public static boolean getBoolean(Context context, int id) { - LogUtil.info(TAG, "Entering getBoolean"); - boolean result = false; - if (context == null) { - LogUtil.error(TAG, "getBoolean -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtil.error(TAG, "getBoolean -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getBoolean(); - } catch (IOException e) { - LogUtil.error(TAG, "getBoolean -> IOException"); - } catch (NotExistException e) { - LogUtil.error(TAG, "getBoolean -> NotExistException"); - } catch (WrongTypeException e) { - LogUtil.error(TAG, "getBoolean -> WrongTypeException"); - } - return result; - } - - /** - * get the string array - * - * @param context the context - * @param id the string array id - * @return the string array - */ - public static String[] getStringArray(Context context, int id) { - LogUtil.info(TAG, "Entering getStringArray"); - String[] result = null; - if (context == null) { - LogUtil.error(TAG, "getStringArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtil.error(TAG, "getStringArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getStringArray(); - } catch (IOException e) { - LogUtil.error(TAG, "getStringArray -> IOException"); - } catch (NotExistException e) { - LogUtil.error(TAG, "getStringArray -> NotExistException"); - } catch (WrongTypeException e) { - LogUtil.error(TAG, "getStringArray -> WrongTypeException"); - } - return result; - } - - /** - * get the int array - * - * @param context the context - * @param id the int array - * @return the int array - */ - public static int[] getIntArray(Context context, int id) { - LogUtil.info(TAG, "Entering getIntArray"); - int[] result = null; - if (context == null) { - LogUtil.error(TAG, "getIntArray -> get null context"); - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - LogUtil.error(TAG, "getIntArray -> get null ResourceManager"); - return result; - } - try { - result = manager.getElement(id).getIntArray(); - } catch (IOException e) { - LogUtil.error(TAG, "getIntArray -> IOException"); - } catch (NotExistException e) { - LogUtil.error(TAG, "getIntArray -> NotExistException"); - } catch (WrongTypeException e) { - LogUtil.error(TAG, "getIntArray -> WrongTypeException"); - } - return result; - } - /** * get the vector drawable * @@ -299,96 +75,4 @@ public class ResUtils { public static VectorElement getVectorDrawable(Context context, int id) { return new VectorElement(context, id); } - - /** - * get the pixel map - * - * @param context the context - * @param id the id - * @return the pixel map - */ - public static Optional getPixelMap(Context context, int id) { - LogUtil.info(TAG, "Entering getPixelMap"); - String path = getPathById(context, id); - if (path == null || path.trim().length() == 0) { - LogUtil.error(TAG, "getPixelMap -> get empty path"); - return Optional.empty(); - } - RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path); - ImageSource.SourceOptions options = new ImageSource.SourceOptions(); - options.formatHint = "image/png"; - ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions(); - try { - Resource asset = assetManager.openRawFile(); - ImageSource source = ImageSource.create(asset, options); - return Optional.ofNullable(source.createPixelmap(decodingOptions)); - } catch (IOException e) { - LogUtil.error(TAG, "getPixelMap -> IOException"); - } - return Optional.empty(); - } - - /** - * get the Pixel Map Element - * - * @param context the context - * @param resId the res id - * @return the Pixel Map Element - */ - public static PixelMapElement getPixelMapDrawable(Context context, int resId) { - LogUtil.info(TAG, "Entering getPixelMapDrawable"); - Optional optional = getPixelMap(context, resId); - return optional.map(PixelMapElement::new).orElse(null); - } - - /** - * get the Element - * - * @param color the color - * @return the Element - */ - public static Element buildDrawableByColor(int color) { - LogUtil.info(TAG, "Entering buildDrawableByColor"); - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - return drawable; - } - - /** - * get the Element By ColorRadius - * - * @param color the color - * @param radius the radius - * @return the Element By ColorRadius - */ - public static Element buildDrawableByColorRadius(int color, float radius) { - LogUtil.info(TAG, "Entering buildDrawableByColorRadius"); - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - drawable.setCornerRadius(radius); - return drawable; - } - - /** - * get the ShapeElement - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param startAngle the start angle - * @param sweepAngle the sweep angle - * @return the ShapeElement - */ - public static ShapeElement getCustomArcGradientDrawable( - int thickness, Color inside, Color border, float startAngle, float sweepAngle) { - LogUtil.info(TAG, "Entering getCustomArcGradientDrawable"); - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.ARC); - drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part - drawable.setArc(new Arc(startAngle, sweepAngle, false)); - drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - return drawable; - } } diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ValueAnimator.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ValueAnimator.java index 9c4088f62b81e9ba1e582441ba021d1e2efc69bf..fc3e5a4c51f832096b73af2cb63a8d78dbac66cc 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ValueAnimator.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/util/ValueAnimator.java @@ -28,9 +28,8 @@ import java.util.Set; * Value Animator */ public class ValueAnimator { - private AnimatorGroup mAnimationGroup = new AnimatorGroup(); + private final AnimatorGroup mAnimationGroup = new AnimatorGroup(); private AnimatorUpdateListener mListener; - private State mState = State.ANIM_NULL; private AnimatorStatusChangeListener mAnimatorStatusChangeListener; /** @@ -159,7 +158,6 @@ public class ValueAnimator { } private void setState(State state) { - this.mState = state; if (state == State.ANIM_CANCEL || state == State.ANIM_END || state == State.ANIM_PAUSE @@ -176,15 +174,6 @@ public class ValueAnimator { } } - /** - * getAnimationState - * - * @return State - */ - public State getAnimationState() { - return mState; - } - /** * addUpdateListener * @@ -224,7 +213,6 @@ public class ValueAnimator { * animation status */ public enum State { - ANIM_NULL, ANIM_START, ANIM_STOP, ANIM_CANCEL, @@ -234,8 +222,8 @@ public class ValueAnimator { } private static class AnimFloat { - private float startF; - private float endF; + private final float startF; + private final float endF; private AnimFloat(float startF, float endF) { this.startF = startF; diff --git a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/view/CameraView.java b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/view/CameraView.java index 6d2bb9cde1c18cbf75d2ad1193ae4ba9f26be6c3..ca5f2e3f86b9a4bb08ba964eebff3ac4e4ff9104 100644 --- a/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/view/CameraView.java +++ b/cameralibrary/src/main/java/com/flask/colorpicker/cameralibrary/view/CameraView.java @@ -1,7 +1,6 @@ package com.flask.colorpicker.cameralibrary.view; import ohos.agp.components.surfaceprovider.SurfaceProvider; -import ohos.app.Context; import ohos.media.image.ImageReceiver; import ohos.media.image.PixelMap; @@ -14,20 +13,11 @@ public interface CameraView { void confirmState(int type); void showPicture(PixelMap bitmap, boolean isVertical); - - void playVideo(String url); - void stopVideo(); - void setTip(String tip); - - void startPreviewCallback(); - - boolean handlerFoucs(float x, float y); + void handlerFoucs(float x, float y); SurfaceProvider getSurfaceProvider(); ImageReceiver getImageReceiver(); - - Context getAppContext(); } diff --git a/entry/src/main/java/com/donkingliang/imageselector/ImageAbility.java b/entry/src/main/java/com/donkingliang/imageselector/ImageAbility.java index 265e1f54552486ae4d54664bb4acb8981cd52c86..d639f11da4e0ca78548b06987f4978202a31d9d2 100644 --- a/entry/src/main/java/com/donkingliang/imageselector/ImageAbility.java +++ b/entry/src/main/java/com/donkingliang/imageselector/ImageAbility.java @@ -25,7 +25,6 @@ import ohos.aafwk.ability.Ability; import ohos.aafwk.ability.DataAbilityHelper; import ohos.aafwk.ability.DataAbilityRemoteException; import ohos.aafwk.content.Intent; -import ohos.agp.components.Component; import ohos.agp.components.Text; import ohos.agp.utils.Color; import ohos.data.rdb.ValuesBucket; @@ -44,27 +43,19 @@ import java.io.OutputStream; /** * 图片裁剪 * - * @author:Hexy + * @author Hexy * @since 2021-04-23 */ public class ImageAbility extends Ability implements CropResult { private UCropView mUcropView; private Text tvLift; - private Text tvRight; private Text tvAmplification; private Text tvLessen; - private Text tvCrop; - private PixelMap.InitializationOptions options; - private PixelMap pixelmap; - private Uri uriPath; - - // 待裁剪图片的URI - private Uri uriI; /** * onStart * - * @param intent + * @param intent intent */ @Override public void onStart(Intent intent) { @@ -73,19 +64,20 @@ public class ImageAbility extends Ability implements CropResult { String urlpath = intent.getStringParam("img"); // 网图URI - uriI = Uri.parse(urlpath); + // 待裁剪图片的URI + Uri uriI = Uri.parse(urlpath); // 本地URI tvLift = (Text) findComponentById(ResourceTable.Id_tv_lift); - tvRight = (Text) findComponentById(ResourceTable.Id_tv_right); + Text tvRight = (Text) findComponentById(ResourceTable.Id_tv_right); tvAmplification = (Text) findComponentById(ResourceTable.Id_tv_amplification); tvLessen = (Text) findComponentById(ResourceTable.Id_tv_lessen); - tvCrop = (Text) findComponentById(ResourceTable.Id_tv_crop); - options = new PixelMap.InitializationOptions(); + Text tvCrop = (Text) findComponentById(ResourceTable.Id_tv_crop); + PixelMap.InitializationOptions options = new PixelMap.InitializationOptions(); options.size = new Size(Constant.IMAGESIZE, Constant.IMAGESIZE); - pixelmap = PixelMap.create(options); + PixelMap pixelmap = PixelMap.create(options); String filename = "test.jpg"; - uriPath = saveImage(filename, pixelmap); + Uri uriPath = saveImage(filename, pixelmap); mUcropView = (UCropView) findComponentById(ResourceTable.Id_ucv_pic); mUcropView.getCropImageView().setImageUri(uriI, uriPath); mUcropView.getOverlayView().setShowCropFrame(true); @@ -93,29 +85,21 @@ public class ImageAbility extends Ability implements CropResult { mUcropView.getOverlayView().setDimmedColor(Color.TRANSPARENT.getValue()); // 裁剪Button - tvCrop.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component component) { - cropAndSaveImage(); - } - }); + tvCrop.setClickedListener(component -> cropAndSaveImage()); // 旋转+90Button - tvRight.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component component) { - float degrees = Constant.NANZOREF; + tvRight.setClickedListener(component -> { + float degrees = Constant.NANZOREF; - // 计算旋转中心 - float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); - float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); + // 计算旋转中心 + float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); + float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); - // 旋转 - mUcropView.getCropImageView().postRotate(degrees, centerX, centerY); + // 旋转 + mUcropView.getCropImageView().postRotate(degrees, centerX, centerY); - // 适配 - mUcropView.getCropImageView().setImageToWrapCropBounds(false); - } + // 适配 + mUcropView.getCropImageView().setImageToWrapCropBounds(false); }); setListener(); @@ -126,57 +110,48 @@ public class ImageAbility extends Ability implements CropResult { */ public void setListener() { // 旋转-90Button - tvLift.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component component) { - float degrees = Constant.NANZOREFU; + tvLift.setClickedListener(component -> { + float degrees = Constant.NANZOREFU; - // 计算旋转中心 - float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); - float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); + // 计算旋转中心 + float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); + float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); - // 旋转 - mUcropView.getCropImageView().postRotate(degrees, centerX, centerY); + // 旋转 + mUcropView.getCropImageView().postRotate(degrees, centerX, centerY); - // 适配 - mUcropView.getCropImageView().setImageToWrapCropBounds(false); - } + // 适配 + mUcropView.getCropImageView().setImageToWrapCropBounds(false); }); // 缩放x2 Button - tvLessen.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component component) { - float factor = Constant.SECONDF; + tvLessen.setClickedListener(component -> { + float factor = Constant.SECONDF; - // 计算旋转中心 - float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); - float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); + // 计算旋转中心 + float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); + float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); - // 旋转 - mUcropView.getCropImageView().postScale(factor, centerX, centerY); + // 旋转 + mUcropView.getCropImageView().postScale(factor, centerX, centerY); - // 适配 - mUcropView.getCropImageView().setImageToWrapCropBounds(true); - } + // 适配 + mUcropView.getCropImageView().setImageToWrapCropBounds(true); }); // 缩放/2 Button - tvAmplification.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component component) { - float factor = Constant.ZOREFIVE; + tvAmplification.setClickedListener(component -> { + float factor = Constant.ZOREFIVE; - // 计算旋转中心 - float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); - float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); + // 计算旋转中心 + float centerX = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointX(); + float centerY = mUcropView.getOverlayView().getCropViewRect().getCenter().getPointY(); - // 旋转 - mUcropView.getCropImageView().postScale(factor, centerX, centerY); + // 旋转 + mUcropView.getCropImageView().postScale(factor, centerX, centerY); - // 适配 - mUcropView.getCropImageView().setImageToWrapCropBounds(false); - } + // 适配 + mUcropView.getCropImageView().setImageToWrapCropBounds(false); }); } @@ -216,7 +191,7 @@ public class ImageAbility extends Ability implements CropResult { if (isResult) { isResult = imagePacker.addImage(pixelMap); if (isResult) { - long dataSize = imagePacker.finalizePacking(); + imagePacker.finalizePacking(); } } try { @@ -247,7 +222,7 @@ public class ImageAbility extends Ability implements CropResult { /** * onForeground * - * @param intent + * @param intent intent */ @Override public void onForeground(Intent intent) { @@ -257,7 +232,7 @@ public class ImageAbility extends Ability implements CropResult { /** * 回調 * - * @param path + * @param path path */ @Override public void onCropResult(String path) { diff --git a/entry/src/main/java/com/donkingliang/imageselector/MainAbility.java b/entry/src/main/java/com/donkingliang/imageselector/MainAbility.java index c1948d7428beacb2ce12c19010e0049b06f61b90..b70e02faa27d8d219fc80e22fb797d490205cd3c 100644 --- a/entry/src/main/java/com/donkingliang/imageselector/MainAbility.java +++ b/entry/src/main/java/com/donkingliang/imageselector/MainAbility.java @@ -50,7 +50,7 @@ import static ohos.bundle.IBundleManager.PERMISSION_GRANTED; /** * 主界面 * - * @author: ImageSelector + * @author ImageSelector * @since 2021-04-19 */ public class MainAbility extends Ability { @@ -61,7 +61,7 @@ public class MainAbility extends Ability { private ArrayList images = new ArrayList<>(); private String img = ""; private int selectType = 0; - private List mPermissions = + private final List mPermissions = new LinkedList<>( Arrays.asList( SystemPermission.WRITE_USER_STORAGE, SystemPermission.CAMERA, SystemPermission.MICROPHONE)); @@ -74,7 +74,7 @@ public class MainAbility extends Ability { /** * onStart * - * @param intent + * @param intent intent */ @Override public void onStart(Intent intent) { @@ -136,7 +136,7 @@ public class MainAbility extends Ability { mPermissions.removeIf(perM -> verifySelfPermission(perM) == PERMISSION_GRANTED || !canRequestPermission(perM)); if (!mPermissions.isEmpty()) { requestPermissionsFromUser( - mPermissions.toArray(new String[mPermissions.size()]), CameraAbility.REQ_PERMISSION_CODE); + mPermissions.toArray(new String[0]), CameraAbility.REQ_PERMISSION_CODE); } else { if (selectType == 1) { choosePic(); @@ -163,9 +163,9 @@ public class MainAbility extends Ability { /** * 权限回调 * - * @param requestCode - * @param ss - * @param grantResults + * @param requestCode requestCode + * @param ss ss + * @param grantResults grantResults */ @Override public void onRequestPermissionsFromUserResult(int requestCode, String[] ss, int[] grantResults) { @@ -219,9 +219,9 @@ public class MainAbility extends Ability { /** * 接受回调的值 * - * @param requestCode - * @param resultCode - * @param resultData + * @param requestCode requestCode + * @param resultCode resultCode + * @param resultData resultData */ @Override protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) { @@ -234,7 +234,7 @@ public class MainAbility extends Ability { if (resultCode == ImagePicker.REQUEST_CODE_PREVIEW || resultCode == ImagePicker.RESULT_CODE_ITEMS && requestCode == Constant.ONWZORE) { - images = (ArrayList) resultData.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS); + images = resultData.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS); if (isCrop) { img = images.get(0).uriSchema; } @@ -257,7 +257,7 @@ public class MainAbility extends Ability { /** * 图片裁剪 * - * @param imgPath + * @param imgPath imgPath */ public void cropImg(String imgPath) { Operation operation = new Intent.OperationBuilder() @@ -280,17 +280,12 @@ public class MainAbility extends Ability { */ private class MyAdapter extends BaseItemProvider { - private List items; + private final List items; MyAdapter(List imageItems) { this.items = imageItems; } - public void setData(List imageItems) { - this.items = imageItems; - notifyDataChanged(); - } - @Override public int getCount() { return items.size(); diff --git a/entry/src/main/java/com/donkingliang/imageselector/MyApplication.java b/entry/src/main/java/com/donkingliang/imageselector/MyApplication.java index 20df47912b3413e1e2d18709ac76daff16fc9bf9..001ee9c6d0416b342cf72ffada24f21bec5edcfe 100644 --- a/entry/src/main/java/com/donkingliang/imageselector/MyApplication.java +++ b/entry/src/main/java/com/donkingliang/imageselector/MyApplication.java @@ -20,7 +20,7 @@ import ohos.aafwk.ability.AbilityPackage; /** * MyApplication * - * @author:Hexy + * @author Hexy * @since 2021-04-23 */ public class MyApplication extends AbilityPackage { diff --git a/entry/src/main/java/com/donkingliang/imageselector/imageloader/UilImageLoader.java b/entry/src/main/java/com/donkingliang/imageselector/imageloader/UilImageLoader.java index 46b14935dbaead138006a0ba7f4843555b349cf8..fcbe894129a60e09b4ff5c99fae2cb2a499db2de 100644 --- a/entry/src/main/java/com/donkingliang/imageselector/imageloader/UilImageLoader.java +++ b/entry/src/main/java/com/donkingliang/imageselector/imageloader/UilImageLoader.java @@ -24,18 +24,18 @@ import ohos.agp.components.Image; /** * 图片加载 * - * @author:ImageSelector + * @author ImageSelector * @since 2021-04-23 */ public class UilImageLoader implements ImageLoader { /** * displayImage * - * @param ability - * @param uriScheme - * @param imageView - * @param width - * @param height + * @param ability ability + * @param uriScheme uriScheme + * @param imageView imageView + * @param width width + * @param height height */ @Override public void displayImage(Ability ability, String uriScheme, Image imageView, int width, int height) { @@ -51,11 +51,11 @@ public class UilImageLoader implements ImageLoader { /** * displayImagePreview * - * @param ability - * @param uriScheme - * @param imageView - * @param width - * @param height + * @param ability ability + * @param uriScheme uriScheme + * @param imageView imageView + * @param width width + * @param height height */ @Override public void displayImagePreview(Ability ability, String uriScheme, Image imageView, int width, int height) { diff --git a/entry/src/main/java/com/donkingliang/imageselector/util/Constant.java b/entry/src/main/java/com/donkingliang/imageselector/util/Constant.java index b167243a560d4ec13a2dd066fa2586ff33dece16..d18297c834fa155d6050d9f2f2adf71d620f498f 100644 --- a/entry/src/main/java/com/donkingliang/imageselector/util/Constant.java +++ b/entry/src/main/java/com/donkingliang/imageselector/util/Constant.java @@ -30,10 +30,6 @@ public class Constant { * numner 2f */ public static final float SECONDF = 2f; - /** - * numner 2 - */ - public static final int SECOND = 2; /** * numner 3 */ diff --git a/entry/src/main/java/com/donkingliang/imageselector/util/HeLog.java b/entry/src/main/java/com/donkingliang/imageselector/util/HeLog.java index eae738616176e456adfa8b8d71df517619f064b9..e19147d82d6760cfd2ae8b5d1a21edf5bcb28316 100644 --- a/entry/src/main/java/com/donkingliang/imageselector/util/HeLog.java +++ b/entry/src/main/java/com/donkingliang/imageselector/util/HeLog.java @@ -21,13 +21,12 @@ import ohos.hiviewdfx.HiLogLabel; /** * 日志打印类 * - * @author:Hexy + * @author Hexy * @since 2021-03-24 */ public final class HeLog { private static final HiLogLabel LABEL_LOG = new HiLogLabel(3, 0xD000f00, "dqh"); private static final String LOG_FORMAT = "%{public}s:%{public}s"; - private static final String TAG = "HeLog"; private HeLog() { } @@ -35,56 +34,11 @@ public final class HeLog { /** * 打印debug日志 * - * @param tag - * @param info + * @param tag tag + * @param info info */ public static void d(String tag, String info) { HiLog.debug(LABEL_LOG, LOG_FORMAT, tag, info); } - /** - * 打印debug日志 - * - * @param info - */ - public static void d(String info) { - d(TAG, info); - } - - /** - * 打印debug日志 - * - * @param info - */ - public static void d(int info) { - d(TAG, info + ""); - } - - /** - * 打印error日志 - * - * @param tag - * @param info - */ - public static void e(String tag, String info) { - HiLog.error(LABEL_LOG, LOG_FORMAT, tag, info); - } - - /** - * 打印error日志 - * - * @param info - */ - public static void e(String info) { - e(TAG, info); - } - - /** - * 打印error日志 - * - * @param info - */ - public static void e(int info) { - e(TAG, info + ""); - } } diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/DataHolder.java b/imagepicker/src/main/java/com/lzy/imagepicker/DataHolder.java index f98857c2adc54ff3984735a86cc17e7b655c7ae8..f9009490636379f36016563c78944847b0ce201c 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/DataHolder.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/DataHolder.java @@ -18,7 +18,7 @@ public class DataHolder { public static final String DH_CURRENT_IMAGE_FOLDER_ITEMS = "dh_current_image_folder_items"; private static DataHolder mInstance; - private Map> data; + private final Map> data; public static DataHolder getInstance() { if (mInstance == null){ diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ImageDataSource.java b/imagepicker/src/main/java/com/lzy/imagepicker/ImageDataSource.java index ec6530f2a4a1e550c7a04a2bac9095ce56b7bc4d..459ea7ec2340908cf3db4fd36c092063b271520c 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ImageDataSource.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/ImageDataSource.java @@ -29,8 +29,6 @@ import java.util.List; */ public class ImageDataSource { - public static final int LOADER_ALL = 0; //加载所有图片 - public static final int LOADER_CATEGORY = 1; //分类加载图片 private final String[] IMAGE_PROJECTION = { //查询图片需要的数据列 AVStorage.Images.Media.DISPLAY_NAME, //图片的显示名称 aaa.jpg AVStorage.Images.Media.DATA, //图片的真实路径 /storage/emulated/0/pp/downloader/wallpaper/aaa.jpg @@ -38,11 +36,11 @@ public class ImageDataSource { AVStorage.Images.Media.MIME_TYPE, //图片的类型 image/jpeg AVStorage.Images.Media.DATE_ADDED}; //图片被添加的时间,long型 1450518608 - private Ability ability; - private OnImagesLoadedListener loadedListener; //图片加载完成的回调接口 - private ArrayList imageFolders = new ArrayList<>(); //所有的图片文件夹 - private DataAbilityHelper helper; - private DataAbilityPredicates dataAbilityPredicates; + private final Ability ability; + private final OnImagesLoadedListener loadedListener; //图片加载完成的回调接口 + private final ArrayList imageFolders = new ArrayList<>(); //所有的图片文件夹 + private final DataAbilityHelper helper; + public DataAbilityPredicates dataAbilityPredicates; private ResultSet resultSet; /** @@ -57,26 +55,17 @@ public class ImageDataSource { helper = DataAbilityHelper.creator(ability); dataAbilityPredicates = new DataAbilityPredicates(); - new Thread(new Runnable() { - @Override - public void run() { - try { - if (path == null) { - resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null); - - } else { - resultSet = helper.query(Uri.getUriFromFile(new File(path)), null, null); - } - ability.getUITaskDispatcher().syncDispatch(new Runnable() { - @Override - public void run() { - onLoadFinished(resultSet); - - } - }); - } catch (DataAbilityRemoteException e) { - onLoadFinished(resultSet); + new Thread(() -> { + try { + if (path == null) { + resultSet = helper.query(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, null, null); + + } else { + resultSet = helper.query(Uri.getUriFromFile(new File(path)), null, null); } + ability.getUITaskDispatcher().syncDispatch(() -> onLoadFinished(resultSet)); + } catch (DataAbilityRemoteException e) { + onLoadFinished(resultSet); } }).start(); @@ -91,6 +80,7 @@ public class ImageDataSource { while (data.goToNextRow()) { String[] all = data.getAllColumnNames(); List a = Arrays.asList(all); + System.out.println(a); //查询数据 String imageName = data.getString(data.getColumnIndexForName(IMAGE_PROJECTION[0])); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ImagePicker.java b/imagepicker/src/main/java/com/lzy/imagepicker/ImagePicker.java index 91e43a9acc79e191a7afcded88d88ad04c6b4c97..fb9d1a4c18cee70a64bf0937008157046bf70ff7 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ImagePicker.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/ImagePicker.java @@ -10,7 +10,6 @@ import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.app.Context; import ohos.app.Environment; -import ohos.media.image.PixelMap; import java.io.File; import java.text.SimpleDateFormat; @@ -34,20 +33,17 @@ import java.util.Locale; */ public class ImagePicker { - public static final String TAG = ImagePicker.class.getSimpleName(); public static final int REQUEST_CODE_TAKE = 1001; public static final int REQUEST_CODE_CROP = 1002; public static final int REQUEST_CODE_PREVIEW = 1003; public static final int RESULT_CODE_ITEMS = 1004; public static final int RESULT_CODE_BACK = 1005; public static final int RESULT_OK = 1001; - public static final int RESULT_CANCELED = 1002; public static final String EXTRA_RESULT_ITEMS = "extra_result_items"; public static final String EXTRA_SELECTED_IMAGE_POSITION = "selected_image_position"; public static final String EXTRA_IMAGE_ITEMS = "extra_image_items"; public static final String EXTRA_FROM_ITEMS = "extra_from_items"; - public static final String EXTRA_TARGET_FILE_PATH = "extra_target_file_path"; private boolean multiMode = true; //图片选择模式 private int selectLimit = 9; //最大选择图片数量 @@ -61,8 +57,7 @@ public class ImagePicker { private ImageLoader imageLoader; //图片加载器 private CropImageView.Style style = CropImageView.Style.RECTANGLE; //裁剪框的形状 private File cropCacheFolder; - private File takeImageFile; - public PixelMap cropBitmap; + public File takeImageFile; private ArrayList mSelectedImages = new ArrayList<>(); //选中的图片集合 private List mImageFolders; //所有的图片文件夹 @@ -166,10 +161,6 @@ public class ImagePicker { return takeImageFile; } - public void setTakeImageFile(File takeImageFile) { - this.takeImageFile = takeImageFile; - } - public File getCropCacheFolder(Context context) { if (cropCacheFolder == null) { cropCacheFolder = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/ImagePicker/cropTemp/"); @@ -177,10 +168,6 @@ public class ImagePicker { return cropCacheFolder; } - public void setCropCacheFolder(File cropCacheFolder) { - this.cropCacheFolder = cropCacheFolder; - } - public ImageLoader getImageLoader() { return imageLoader; } @@ -197,18 +184,10 @@ public class ImagePicker { this.style = style; } - public List getImageFolders() { - return mImageFolders; - } - public void setImageFolders(List imageFolders) { mImageFolders = imageFolders; } - public int getCurrentImageFolderPosition() { - return mCurrentImageFolderPosition; - } - public void setCurrentImageFolderPosition(int mCurrentSelectedImageSetPosition) { mCurrentImageFolderPosition = mCurrentSelectedImageSetPosition; } @@ -277,24 +256,15 @@ public class ImagePicker { public static File createFile(File folder, String prefix, String suffix) { if (!folder.exists() || !folder.isDirectory()) { boolean mkdirs = folder.mkdirs(); + if(mkdirs){ + System.out.println(); + } } SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA); String filename = prefix + dateFormat.format(new Date(System.currentTimeMillis())) + suffix; return new File(folder, filename); } - /** - * 扫描图片 - * @param context 上下文对象 - * @param file 目标文件 - */ - public static void galleryAddPic(Context context, File file) { -// Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); -// Uri contentUri = Uri.getUriFromFile(file); -// mediaScanIntent.setData(contentUri); -// context.sendBroadcast(mediaScanIntent); - } - /** * 图片选中的监听 */ @@ -336,10 +306,6 @@ public class ImagePicker { l.onImageSelected(position, item, isAdd); } } - - /** - * 用于手机内存不足,进程被系统回收,重启时的状态恢复 - */ // public void restoreInstanceState(Bundle savedInstanceState) { // cropCacheFolder = (File) savedInstanceState.getSerializable("cropCacheFolder"); // takeImageFile = (File) savedInstanceState.getSerializable("takeImageFile"); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageFolderAdapter.java b/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageFolderAdapter.java index 6c0a784ff3c616897bbb77c86326ca919e7bae90..78f43ab50265b75bc68c6958c8e953b02ee879d4 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageFolderAdapter.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageFolderAdapter.java @@ -22,10 +22,10 @@ import java.util.List; */ public class ImageFolderAdapter extends BaseItemProvider { - private ImagePicker imagePicker; - private Ability mActivity; - private LayoutScatter mInflater; - private int mImageSize; + private final ImagePicker imagePicker; + private final Ability mActivity; + private final LayoutScatter mInflater; + private final int mImageSize; private List imageFolders; private int lastSelected = 0; @@ -36,7 +36,7 @@ public class ImageFolderAdapter extends BaseItemProvider { imagePicker = ImagePicker.getInstance(); mImageSize = Utils.getImageItemWidth(mActivity); - mInflater = (LayoutScatter)LayoutScatter.getInstance(ability) ; + mInflater = LayoutScatter.getInstance(ability); } public void refreshData(List folders) { @@ -97,7 +97,7 @@ public class ImageFolderAdapter extends BaseItemProvider { return lastSelected; } - private class ViewHolder { + private static class ViewHolder { Image cover; Text folderName; Text imageCount; diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImagePageAdapter.java b/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImagePageAdapter.java index d8df69f1bf4ea1bf0b76ddaf7a8cd10688ba7646..4c89964971bab53cf3f73db56acd776af0c87577 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImagePageAdapter.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImagePageAdapter.java @@ -24,11 +24,11 @@ import ohos.agp.window.service.DisplayManager; */ public class ImagePageAdapter extends PageSliderProvider { - private int screenWidth; - private int screenHeight; - private ImagePicker imagePicker; - private ArrayList images = new ArrayList<>(); - private Ability ability; + private final int screenWidth; + private final int screenHeight; + private final ImagePicker imagePicker; + private ArrayList images; + private final Ability ability; public PhotoViewClickListener listener; public ImagePageAdapter(Ability ability, ArrayList images) { @@ -68,12 +68,9 @@ public class ImagePageAdapter extends PageSliderProvider { imagePicker.getImageLoader().displayImagePreview(ability, imageItem.uriSchema, photoView, screenWidth, screenHeight); } - photoView.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component component) { - if (listener != null) listener.OnPhotoTapListener(component, 0, 0); + photoView.setClickedListener(component -> { + if (listener != null) listener.OnPhotoTapListener(component, 0, 0); - } }); componentContainer.addComponent(photoView); return photoView; diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageRecyclerProvider.java b/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageRecyclerProvider.java index 233a2c090d7aa08f34174756b2fa03a96be1fff0..5b27ca61706b2c6cf4d927586c960efeebef12e3 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageRecyclerProvider.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/adapter/ImageRecyclerProvider.java @@ -36,13 +36,13 @@ public class ImageRecyclerProvider extends RecycleItemProvider { private static final int ITEM_TYPE_CAMERA = 0; //第一个条目是相机 private static final int ITEM_TYPE_NORMAL = 1; //第一个条目不是相机 - private ImagePicker imagePicker; - private Ability ability; + private final ImagePicker imagePicker; + private final Ability ability; private ArrayList images; //当前需要显示的所有的图片数据 - private ArrayList mSelectedImages; //全局保存的已经选中的图片数据 - private boolean isShowCamera; //是否显示拍照按钮 - private int mImageSize; //每个条目的大小 - private LayoutScatter mInflater; + private final ArrayList mSelectedImages; //全局保存的已经选中的图片数据 + private final boolean isShowCamera; //是否显示拍照按钮 + private final int mImageSize; //每个条目的大小 + private final LayoutScatter mInflater; private OnImageItemClickListener listener; //图片被点击的监听 public void setOnImageItemClickListener(OnImageItemClickListener listener) { @@ -61,6 +61,9 @@ public class ImageRecyclerProvider extends RecycleItemProvider { /** * 构造方法 + * + * @param ability ability + * @param images images */ public ImageRecyclerProvider(Ability ability, ArrayList images) { this.ability = ability; @@ -151,24 +154,18 @@ public class ImageRecyclerProvider extends RecycleItemProvider { imagePicker.getImageLoader().displayImage(ability, imageItem.uriSchema, ivThumb, mImageSize, mImageSize); //显示图片 } - ivThumb.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component v) { - if (listener != null) listener.onImageItemClick(rootView, imageItem, position); - } + ivThumb.setClickedListener(v -> { + if (listener != null) listener.onImageItemClick(rootView, imageItem, position); }); - checkView.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component v) { - cbCheck.setChecked(!cbCheck.isChecked()); - int selectLimit = imagePicker.getSelectLimit(); - if (cbCheck.isChecked() && mSelectedImages.size() >= selectLimit) { - cbCheck.setChecked(false); - mask.setVisibility(Component.HIDE); - } else { - imagePicker.addSelectedImageItem(position, imageItem, cbCheck.isChecked(),1); - mask.setVisibility(Component.VISIBLE); - } + checkView.setClickedListener(v -> { + cbCheck.setChecked(!cbCheck.isChecked()); + int selectLimit = imagePicker.getSelectLimit(); + if (cbCheck.isChecked() && mSelectedImages.size() >= selectLimit) { + cbCheck.setChecked(false); + mask.setVisibility(Component.HIDE); + } else { + imagePicker.addSelectedImageItem(position, imageItem, cbCheck.isChecked(),1); + mask.setVisibility(Component.VISIBLE); } }); StateElement stateElement = new StateElement(); @@ -208,14 +205,11 @@ public class ImageRecyclerProvider extends RecycleItemProvider { void bindCamera() { mItemView.setLayoutConfig(new ListContainer.LayoutConfig(mImageSize, mImageSize)); //让图片是个正方形 mItemView.setTag(null); - mItemView.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component v) { - if (ability.verifySelfPermission(SystemPermission.CAMERA) != IBundleManager.PERMISSION_GRANTED) { - ability.requestPermissionsFromUser(new String[]{SystemPermission.CAMERA}, ImageGridAbility.REQUEST_PERMISSION_CAMERA); - } else { - imagePicker.takePicture(ability); - } + mItemView.setClickedListener(v -> { + if (ability.verifySelfPermission(SystemPermission.CAMERA) != IBundleManager.PERMISSION_GRANTED) { + ability.requestPermissionsFromUser(new String[]{SystemPermission.CAMERA}, ImageGridAbility.REQUEST_PERMISSION_CAMERA); + } else { + imagePicker.takePicture(ability); } }); } diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageFolder.java b/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageFolder.java index e76f94d7d2eaf333fdbe39039cdf71c40a62c5ba..02fded0afde23d23bd25febd25cf01afbb7032d7 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageFolder.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageFolder.java @@ -2,7 +2,6 @@ package com.lzy.imagepicker.bean; import java.io.Serializable; import java.util.ArrayList; -import java.util.List; /** * ================================================ diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageItem.java b/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageItem.java index 036c7fa5219ee71783053d740fc0151f8292097a..929af199efb23f201cf53d0d99348a45f5d5b3a6 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageItem.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/bean/ImageItem.java @@ -69,19 +69,15 @@ public class ImageItem implements Serializable, Sequenceable { this.mimeType = in.readString(); this.addTime = in.readLong(); this.checkbox = in.readBoolean(); - } - public static final Sequenceable.Producer PRODUCER = new Sequenceable.Producer() { - @Override - public ImageItem createFromParcel(Parcel source) { - return new ImageItem(source); - } + System.out.println(PRODUCER); + } -// @Override + // @Override // public ImageItem[] newArray(int size) { // return new ImageItem[size]; // } - }; + public static final Sequenceable.Producer PRODUCER = ImageItem::new; @Override public boolean marshalling(Parcel parcel) { diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/loader/ImageLoader.java b/imagepicker/src/main/java/com/lzy/imagepicker/loader/ImageLoader.java index 574bfe84641d9ae4f3e090c840eac40cb94413a8..fb106c2cc90a22e7987d755ce8ece780ed9b8552 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/loader/ImageLoader.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/loader/ImageLoader.java @@ -1,9 +1,7 @@ package com.lzy.imagepicker.loader; import ohos.aafwk.ability.Ability; -import ohos.aafwk.ability.AbilitySlice; import ohos.agp.components.Image; -import ohos.utils.net.Uri; import java.io.Serializable; diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageBaseAbility.java b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageBaseAbility.java index a2541b07798d92525dd7381ad83110ac77f76740..5deee1a0c9878f32bc2f2675c984f3e73ddd02eb 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageBaseAbility.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageBaseAbility.java @@ -3,10 +3,8 @@ package com.lzy.imagepicker.ui; import com.lzy.imagepicker.ResourceTable; import ohos.aafwk.ability.Ability; -import ohos.aafwk.ability.AbilitySlice; import ohos.aafwk.content.Intent; import ohos.agp.window.dialog.ToastDialog; -import ohos.bundle.IBundleManager; /** * ================================================ @@ -29,10 +27,6 @@ public class ImageBaseAbility extends Ability { } - public boolean checkPermission(String permission) { - return verifySelfPermission(permission) == IBundleManager.PERMISSION_GRANTED; - } - public void showToast(String toastText) { if (dialog == null) { dialog = new ToastDialog(this); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageCropAbility.java b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageCropAbility.java index 0a00cceb677e797e5a083779f15ad710e739f114..34049c8989627c8c7a2bd5cbd1eb3178cd9b9abe 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageCropAbility.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageCropAbility.java @@ -15,13 +15,11 @@ import ohos.aafwk.content.Intent; import ohos.agp.components.Button; import ohos.agp.components.Component; import ohos.agp.components.ComponentState; -import ohos.agp.components.Image; import ohos.agp.components.Text; import ohos.media.image.ImageSource; import ohos.media.image.PixelMap; import ohos.media.image.common.PixelFormat; import ohos.media.image.common.Rect; -import ohos.media.image.common.Size; import ohos.utils.net.Uri; import java.io.File; @@ -85,14 +83,13 @@ public class ImageCropAbility extends ImageBaseAbility implements Component.Clic options.allowPartialImage = true; ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions(); sourceOptions.formatHint = "image/png"; - PixelMap pixelMap; try { - pixelMap = ImageSource.create(DataAbilityHelper.creator(this).openFile(Uri.parse(imagePath), "r"), sourceOptions).createPixelmap(options); + ImageSource.create(DataAbilityHelper.creator(this).openFile(Uri.parse(imagePath), "r"), sourceOptions).createPixelmap(options); } catch (DataAbilityRemoteException | FileNotFoundException e) { - pixelMap = null; + System.out.println(); } - int[] screenSze = Utils.getScreenSize(this); + Utils.getScreenSize(this); // options.sampleSize = calculateInSampleSize(options, screenSze[0], screenSze[1]); options.allowPartialImage = false; try { @@ -118,21 +115,6 @@ public class ImageCropAbility extends ImageBaseAbility implements Component.Clic // mCropImageView.setImageBitmap(mCropImageView.rotate(mBitmap, BitmapUtil.getBitmapDegree(imagePath))); } - - public int calculateInSampleSize(ImageSource.DecodingOptions options, int reqWidth, int reqHeight) { - int width = options.desiredSize.width; - int height = options.desiredSize.height; - int inSampleSize = 1; - if (height > reqHeight || width > reqWidth) { - if (width > height) { - inSampleSize = width / reqWidth; - } else { - inSampleSize = height / reqHeight; - } - } - return inSampleSize; - } - @Override public void onClick(Component v) { int id = v.getId(); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageGridAbility.java b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageGridAbility.java index a78bcb3ed65edc8cb6ba05df9ec16b9da1677d2c..769ff006ddce0e40f7aab49c04633569ce32fc0c 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageGridAbility.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImageGridAbility.java @@ -10,7 +10,6 @@ import com.lzy.imagepicker.bean.ImageItem; import com.lzy.imagepicker.util.ElementUtil; import com.lzy.imagepicker.util.ResUtil; import com.lzy.imagepicker.view.FolderPopUpWindow; -import ohos.aafwk.ability.Ability; import ohos.aafwk.content.Intent; import ohos.aafwk.content.Operation; import ohos.agp.components.*; @@ -47,8 +46,6 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc private boolean isOrigin = false; // 是否选中原图 private Component mFooterBar; // 底部栏 private Button mBtnOk; // 确定按钮 - private Image mBtnBack; // 确定按钮 - private Component mllDir; // 文件夹切换按钮 private Text mtvDir; // 显示当前文件夹 private Text mBtnPre; // 预览按钮 private ImageFolderAdapter mImageFolderAdapter; // 图片文件夹的适配器 @@ -81,7 +78,7 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc takePic(); } } - ArrayList images = (ArrayList) data.getSerializableParam(EXTRAS_IMAGES); + ArrayList images = data.getSerializableParam(EXTRAS_IMAGES); imagePicker.setSelectedImages(images); } @@ -90,7 +87,8 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc tableLayoutManager.setColumnCount(3); listContainer.setLayoutManager(tableLayoutManager); - mBtnBack = (Image) findComponentById(ResourceTable.Id_btn_back); + // 确定按钮 + Image mBtnBack = (Image) findComponentById(ResourceTable.Id_btn_back); mBtnBack.setClickedListener(this); mBtnOk = (Button) findComponentById(ResourceTable.Id_btn_ok); @@ -102,7 +100,8 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc mBtnPre = (Text) findComponentById(ResourceTable.Id_btn_preview); mBtnPre.setClickedListener(this); mFooterBar = findComponentById(ResourceTable.Id_footer_bar); - mllDir = findComponentById(ResourceTable.Id_ll_dir); + // 文件夹切换按钮 + Component mllDir = findComponentById(ResourceTable.Id_ll_dir); mllDir.setClickedListener(this); mtvDir = (Text) findComponentById(ResourceTable.Id_tv_dir); if (imagePicker.isMultiMode()) { @@ -207,18 +206,15 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc */ private void createPopupFolderList() { mFolderPopupWindow = new FolderPopUpWindow(this, mImageFolderAdapter); - mFolderPopupWindow.setOnItemClickListener(new FolderPopUpWindow.OnItemClickListener() { - @Override - public void onItemClick(ListContainer listContainer, Component view, int position, long l) { - mImageFolderAdapter.setSelectIndex(position); - imagePicker.setCurrentImageFolderPosition(position); - mFolderPopupWindow.hide(); - ImageFolder imageFolder = (ImageFolder) listContainer.getItemProvider().getItem(position); - if (null != imageFolder) { + mFolderPopupWindow.setOnItemClickListener((listContainer, view, position, l) -> { + mImageFolderAdapter.setSelectIndex(position); + imagePicker.setCurrentImageFolderPosition(position); + mFolderPopupWindow.hide(); + ImageFolder imageFolder = (ImageFolder) listContainer.getItemProvider().getItem(position); + if (null != imageFolder) { // mImageGridAdapter.refreshData(imageFolder.images); - listProvider.refreshData(imageFolder.images); - mtvDir.setText(imageFolder.name); - } + listProvider.refreshData(imageFolder.images); + mtvDir.setText(imageFolder.name); } }); mFolderPopupWindow.setMargin(mFooterBar.getHeight()); @@ -253,12 +249,6 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc .build(); intent.setOperation(operation); intent.setParam(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position); - - /** - * 2017-03-20 - * - * 依然采用弱引用进行解决,采用单例加锁方式处理 - */ // 据说这样会导致大量图片的时候崩溃 // intent.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, imagePicker.getCurrentImageFolderItems()); @@ -270,8 +260,8 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc imagePicker.clearSelectedImages(); imagePicker.addSelectedImageItem(position, imagePicker.getCurrentImageFolderItems().get(position), true,1); + Intent intent = new Intent(); if (imagePicker.isCrop()) { - Intent intent = new Intent(); Operation operation = new Intent.OperationBuilder() .withDeviceId("") .withBundleName(getBundleName()) @@ -280,7 +270,6 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc intent.setOperation(operation); startAbilityForResult(intent, ImagePicker.REQUEST_CODE_CROP); //单选需要裁剪,进入裁剪界面 } else { - Intent intent = new Intent(); intent.setParam(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages()); setResult(ImagePicker.RESULT_CODE_ITEMS, intent); //单选不需要裁剪,返回数据 terminateAbility(); @@ -337,17 +326,16 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc //点击 X , 没有选择照片 if (data.getSerializableParam(ImagePicker.EXTRA_RESULT_ITEMS) == null) { //什么都不做 直接调起相机 - terminateAbility(); + System.out.println(""+data); } else { //说明是从裁剪页面过来的数据,直接返回就可以 if(resultCode == 10001) { setResult(ImagePicker.RESULT_CODE_ITEMS, data); - terminateAbility(); }else{ setResult(ImagePicker.REQUEST_CODE_TAKE, data); - terminateAbility(); } } + terminateAbility(); } } else { @@ -357,18 +345,14 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc //发送广播通知图片增加了 // ImagePicker.galleryAddPic(this, imagePicker.getTakeImageFile()); - - /** - * 2017-03-21 对机型做旋转处理 - */ String path = imagePicker.getTakeImageFile().getAbsolutePath(); ImageItem imageItem = new ImageItem(); imageItem.uriSchema = path; imagePicker.clearSelectedImages(); imagePicker.addSelectedImageItem(0, imageItem, true,1); + Intent intent = new Intent(); if (imagePicker.isCrop()) { - Intent intent = new Intent(); Operation operation = new Intent.OperationBuilder() .withDeviceId("") .withBundleName(getBundleName()) @@ -377,7 +361,6 @@ public class ImageGridAbility extends ImageBaseAbility implements ImageDataSourc intent.setOperation(operation); startAbilityForResult(intent, ImagePicker.REQUEST_CODE_CROP); //单选需要裁剪,进入裁剪界面 } else { - Intent intent = new Intent(); intent.setParam(ImagePicker.EXTRA_RESULT_ITEMS, imagePicker.getSelectedImages()); setResult(ImagePicker.RESULT_CODE_ITEMS, intent); //单选不需要裁剪,返回数据 terminateAbility(); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewAbility.java b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewAbility.java index 6c21221f74fff05a3dc71293182b794dd75d49fb..33814940888ceb1f7bdf67c25327311b4e64aec4 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewAbility.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewAbility.java @@ -4,7 +4,6 @@ package com.lzy.imagepicker.ui; import com.lzy.imagepicker.ImagePicker; import com.lzy.imagepicker.ResourceTable; import com.lzy.imagepicker.bean.ImageItem; -import com.lzy.imagepicker.util.AnimatorUtil; import com.lzy.imagepicker.util.ElementUtil; import com.lzy.imagepicker.util.Formatter; import com.lzy.imagepicker.util.ResUtil; @@ -30,14 +29,10 @@ public class ImagePreviewAbility extends ImagePreviewBaseAbility implements Imag private SuperCheckBox mCbCheck; //是否选中当前图片的Checkbox private SuperCheckBox mCbOrigin; //原图 private Button mBtnOk; //确认图片的选择 - private Component bottomBar; - private Component marginView; - private String preview = ""; @Override protected void onStart(Intent intent) { super.onStart(intent); - preview = intent.getStringParam("preview"); isOrigin = intent.getBooleanParam(ImagePreviewAbility.ISORIGIN, false); imagePicker.addOnImageSelectedListener(this); mBtnOk = (Button) findComponentById(ResourceTable.Id_btn_ok); @@ -48,12 +43,11 @@ public class ImagePreviewAbility extends ImagePreviewBaseAbility implements Imag .addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, ResUtil.getElement(this, ResourceTable.Graphic_bg_btn_nor)) .bind(mBtnOk); - bottomBar = findComponentById(ResourceTable.Id_bottom_bar); + Component bottomBar = findComponentById(ResourceTable.Id_bottom_bar); bottomBar.setVisibility(Component.VISIBLE); mCbCheck = (SuperCheckBox) findComponentById(ResourceTable.Id_cb_check); mCbOrigin = (SuperCheckBox) findComponentById(ResourceTable.Id_cb_origin); - marginView = findComponentById(ResourceTable.Id_margin_bottom); mCbOrigin.setText(ResUtil.getString(this, ResourceTable.String_ip_origin)); mCbOrigin.setCheckedStateChangedListener(this); mCbOrigin.setChecked(isOrigin); @@ -99,21 +93,18 @@ public class ImagePreviewAbility extends ImagePreviewBaseAbility implements Imag }); // 当点击当前选中按钮的时候,需要根据当前的选中状态添加和移除图片 - mCbCheck.setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component v) { - ImageItem imageItem = mImageItems.get(mCurrentPosition); - int selectLimit = imagePicker.getSelectLimit(); + mCbCheck.setClickedListener(v -> { + ImageItem imageItem = mImageItems.get(mCurrentPosition); + int selectLimit = imagePicker.getSelectLimit(); // if (selectedImages.size() >= selectLimit - 1) { // mCbCheck.setClickable(false); // return; // } - if (mCbCheck.isChecked() && selectedImages.size() >= selectLimit - 1) { - imagePicker.addSelectedImageItem(mCurrentPosition, imageItem, false, 1); - } else { - boolean isChecked = mCbCheck.isChecked(); - imagePicker.addSelectedImageItem(mCurrentPosition, imageItem, !isChecked, 1); - } + if (mCbCheck.isChecked() && selectedImages.size() >= selectLimit - 1) { + imagePicker.addSelectedImageItem(mCurrentPosition, imageItem, false, 1); + } else { + boolean isChecked = mCbCheck.isChecked(); + imagePicker.addSelectedImageItem(mCurrentPosition, imageItem, !isChecked, 1); } }); } diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewBaseAbility.java b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewBaseAbility.java index 7c10ed9ab620bc811863a3b24d4fb8240cf1508a..adee8ebd6016650856014d25fa2166f6482e7e09 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewBaseAbility.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewBaseAbility.java @@ -47,7 +47,7 @@ public abstract class ImagePreviewBaseAbility extends ImageBaseAbility { if (isFromItems) { // 据说这样会导致大量图片崩溃 - mImageItems = (ArrayList) getIntent().getSerializableParam(ImagePicker.EXTRA_IMAGE_ITEMS); + mImageItems = getIntent().getSerializableParam(ImagePicker.EXTRA_IMAGE_ITEMS); } else { // 下面采用弱引用会导致预览崩溃 mImageItems = (ArrayList) DataHolder.getInstance().retrieve(DataHolder.DH_CURRENT_IMAGE_FOLDER_ITEMS); @@ -67,23 +67,13 @@ public abstract class ImagePreviewBaseAbility extends ImageBaseAbility { // topBar.setLayoutConfig(params); // } topBar.findComponentById(ResourceTable.Id_btn_ok).setVisibility(Component.HIDE); - topBar.findComponentById(ResourceTable.Id_btn_back).setClickedListener(new Component.ClickedListener() { - @Override - public void onClick(Component v) { - terminateAbility(); - } - }); + topBar.findComponentById(ResourceTable.Id_btn_back).setClickedListener(v -> terminateAbility()); mTitleCount = (Text) findComponentById(ResourceTable.Id_tv_des); mViewPager = (PageSlider) findComponentById(ResourceTable.Id_viewpager); pro = new ImagePageAdapter(this, mImageItems); - pro.setPhotoViewClickListener(new ImagePageAdapter.PhotoViewClickListener() { - @Override - public void OnPhotoTapListener(Component view, float v, float v1) { - onImageSingleTap(); - } - }); + pro.setPhotoViewClickListener((view, v, v1) -> onImageSingleTap()); mViewPager.setProvider(pro); mViewPager.setCurrentPage(mCurrentPosition, true); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewDelAbility.java b/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewDelAbility.java deleted file mode 100644 index 7c32d222627ad6cff81d84a35b4069d2b78bedef..0000000000000000000000000000000000000000 --- a/imagepicker/src/main/java/com/lzy/imagepicker/ui/ImagePreviewDelAbility.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.lzy.imagepicker.ui; - - -import com.lzy.imagepicker.ImagePicker; -import com.lzy.imagepicker.ResourceTable; -import com.lzy.imagepicker.util.AnimatorUtil; -import com.lzy.imagepicker.util.ResUtil; -import ohos.aafwk.content.Intent; -import ohos.agp.components.Component; -import ohos.agp.components.Image; -import ohos.agp.components.PageSlider; -import ohos.agp.window.dialog.CommonDialog; -import ohos.agp.window.dialog.IDialog; - -/** - * ================================================ - * 作 者:jeasonlzy(廖子尧),ikkong (ikkong@163.com) - * 版 本:1.0 - * 创建日期:2016/5/19 - * 描 述: - * 修订历史:预览已经选择的图片,并可以删除, 感谢 ikkong 的提交 - * ================================================ - */ -public class ImagePreviewDelAbility extends ImagePreviewBaseAbility implements Component.ClickedListener { - - @Override - protected void onStart(Intent intent) { - super.onStart(intent); - Image mBtnDel = (Image) findComponentById(ResourceTable.Id_btn_del); - mBtnDel.setClickedListener(this); - mBtnDel.setVisibility(Component.VISIBLE); - topBar.findComponentById(ResourceTable.Id_btn_back).setClickedListener(this); - - mTitleCount.setText(ResUtil.getString(this, ResourceTable.String_ip_preview_image_count, mCurrentPosition + 1, mImageItems.size())); - //滑动ViewPager的时候,根据外界的数据改变当前的选中状态和当前的图片的位置描述文本 - mViewPager.addPageChangedListener(new PageSlider.PageChangedListener() { - @Override - public void onPageSliding(int i, float v, int i1) { - - } - - @Override - public void onPageSlideStateChanged(int i) { - - } - - @Override - public void onPageChosen(int position) { - mCurrentPosition = position; - mTitleCount.setText(ResUtil.getString(ImagePreviewDelAbility.this, ResourceTable.String_ip_preview_image_count, mCurrentPosition + 1, mImageItems.size())); - } - - }); - } - - - @Override - public void onClick(Component v) { - int id = v.getId(); - if (id == ResourceTable.Id_btn_del) { - showDeleteDialog(); - } else if (id == ResourceTable.Id_btn_back) { - onBackPressed(); - } - } - - /** - * 是否删除此张图片 - */ - private void showDeleteDialog() { - - CommonDialog dialog = new CommonDialog(this); - dialog.setTitleText("提示"); - dialog.setContentText("要删除这张照片吗?"); - dialog.setButton(0, "取消", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - dialog.hide(); - } - }); - dialog.setButton(1, "确定", new IDialog.ClickedListener() { - @Override - public void onClick(IDialog iDialog, int i) { - //移除当前图片刷新界面 - mImageItems.remove(mCurrentPosition); - if (mImageItems.size() > 0) { - pro.setData(mImageItems); - pro.notifyDataChanged(); - mTitleCount.setText(ResUtil.getString(ImagePreviewDelAbility.this, ResourceTable.String_ip_preview_image_count, mCurrentPosition + 1, mImageItems.size())); - } else { - onBackPressed(); - } - } - }); - dialog.show(); - - } - - @Override - public void onBackPressed() { - Intent intent = new Intent(); - //带回最新数据 - intent.setParam(ImagePicker.EXTRA_IMAGE_ITEMS, mImageItems); - setResult(ImagePicker.RESULT_CODE_BACK, intent); - terminateAbility(); - super.onBackPressed(); - } - - /** - * 单击时,隐藏头和尾 - */ - @Override - public void onImageSingleTap() { - if (topBar.getVisibility() == Component.VISIBLE) { - AnimatorUtil.topOut(topBar); - topBar.setVisibility(Component.HIDE); - //给最外层布局加上这个属性表示,Activity全屏显示,且状态栏被隐藏覆盖掉。 -// if (Build.VERSION.SDK_INT >= 16) content.setSystemUiVisibility(Component.SYSTEM_UI_FLAG_FULLSCREEN); - } else { - AnimatorUtil.topIn(topBar); - topBar.setVisibility(Component.VISIBLE); - //Activity全屏显示,但状态栏不会被隐藏覆盖,状态栏依然可见,Activity顶端布局部分会被状态遮住 -// if (Build.VERSION.SDK_INT >= 16) content.setSystemUiVisibility(Component.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); - } - } -} \ No newline at end of file diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/util/AnimatorUtil.java b/imagepicker/src/main/java/com/lzy/imagepicker/util/AnimatorUtil.java deleted file mode 100644 index 6ce8939752a3bb41d9d95ba48d1f05f20f3a0ce8..0000000000000000000000000000000000000000 --- a/imagepicker/src/main/java/com/lzy/imagepicker/util/AnimatorUtil.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.lzy.imagepicker.util; - -import ohos.agp.animation.AnimatorProperty; -import ohos.agp.components.Component; - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; - -public class AnimatorUtil { - - - - public static void fadeOut(Component component) { - AnimatorProperty anim = component.createAnimatorProperty(); - try { - Method alphaFrom = AnimatorProperty.class.getDeclaredMethod("alphaFrom", float.class); - alphaFrom.setAccessible(true); - alphaFrom.invoke(anim, 1); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - anim.alphaFrom(component.getAlpha()); - } - anim.alpha(0).setDuration(400); - anim.start(); - } - - public static void fadeIn(Component component) { - AnimatorProperty anim = component.createAnimatorProperty(); - try { - Method alphaFrom = AnimatorProperty.class.getDeclaredMethod("alphaFrom", float.class); - alphaFrom.setAccessible(true); - alphaFrom.invoke(anim, 0); - } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { - anim.alphaFrom(0); - } - anim.alpha(1).setDuration(400); - anim.start(); - } - - - public static void topOut(Component component) { - AnimatorProperty anim = component.createAnimatorProperty(); - anim.moveFromY(0).moveToY(-component.getHeight()).setDuration(400); - anim.start(); - } - - public static void topIn(Component component) { - AnimatorProperty anim = component.createAnimatorProperty(); - anim.moveFromY(-component.getHeight()).moveToY(0).setDuration(400); - anim.start(); - } - - -} diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/util/BitmapUtil.java b/imagepicker/src/main/java/com/lzy/imagepicker/util/BitmapUtil.java index d267fb584f2065292aa2fdba5b2fc8ef8539c591..27baa832fe80346c8610652c2af7edc6682679da 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/util/BitmapUtil.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/util/BitmapUtil.java @@ -24,47 +24,13 @@ public class BitmapUtil { throw new UnsupportedOperationException("u can't instantiate me..."); } - /** - * 获取图片的旋转角度 - * - * @param path 图片绝对路径 - * @return 图片的旋转角度 - */ - public static int getBitmapDegree(String path) { - int degree = 0; - try { - // 从指定路径下读取图片,并获取其EXIF信息 - ImageSource imageSource = ImageSource.create(path, new ImageSource.SourceOptions()); -// ExifInterface exifInterface = new ExifInterface(path); - // 获取图片的旋转信息 - int orietation = imageSource.getImagePropertyInt(PropertyKey.Exif.ORIENTATION, 0); - degree = orietation; -// int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); -// switch (orientation) { -// case ExifInterface.ORIENTATION_ROTATE_90: -// degree = 90; -// break; -// case ExifInterface.ORIENTATION_ROTATE_180: -// degree = 180; -// break; -// case ExifInterface.ORIENTATION_ROTATE_270: -// degree = 270; -// break; -// } - } catch (Exception e) { - return degree; - } - return degree; - } - public static int getBitmapDegree(Ability ability, String uriScheme) { int degree = 0; try { DataAbilityHelper helper = DataAbilityHelper.creator(ability); ImageSource.SourceOptions options = new ImageSource.SourceOptions(); ImageSource source = ImageSource.create(helper.openFile(Uri.parse(uriScheme), "r"), options); - int orietation = source.getImagePropertyInt(PropertyKey.Exif.ORIENTATION, 0); - degree = orietation; + degree = source.getImagePropertyInt(PropertyKey.Exif.ORIENTATION, 0); } catch (DataAbilityRemoteException | FileNotFoundException e) { return degree; } diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/util/ElementUtil.java b/imagepicker/src/main/java/com/lzy/imagepicker/util/ElementUtil.java index c8df401291db33337d40400dd77ed4e1a4200a67..14f579e73313f8dd383f902e9062db3966a60976 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/util/ElementUtil.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/util/ElementUtil.java @@ -1,6 +1,5 @@ package com.lzy.imagepicker.util; -import ohos.aafwk.ability.Ability; import ohos.agp.components.Component; import ohos.agp.components.element.Element; import ohos.agp.components.element.StateElement; @@ -10,7 +9,7 @@ public class ElementUtil { public static class StateElementBuilder { - private StateElement stateElement; + private final StateElement stateElement; public StateElementBuilder() { stateElement = new StateElement(); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/util/Formatter.java b/imagepicker/src/main/java/com/lzy/imagepicker/util/Formatter.java index 24843eb9a49a952c006d02939dcd748fab693cad..aea7eb36e9c71c50b2463960fd894b2ada1a8daf 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/util/Formatter.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/util/Formatter.java @@ -1,35 +1,16 @@ package com.lzy.imagepicker.util; -import com.lzy.imagepicker.ui.ImagePreviewAbility; import ohos.app.Context; -import java.util.Locale; - public class Formatter { - - /** - * @hide - */ public static final long KB_IN_BYTES = 1024; - /** - * @hide - */ public static final long MB_IN_BYTES = KB_IN_BYTES * 1024; - /** - * @hide - */ public static final long GB_IN_BYTES = MB_IN_BYTES * 1024; - /** - * @hide - */ public static final long TB_IN_BYTES = GB_IN_BYTES * 1024; - /** - * @hide - */ public static final long PB_IN_BYTES = TB_IN_BYTES * 1024; public static final int FLAG_CALCULATE_ROUNDED = 1 << 1; - public static final int FLAG_SHORTER = 1 << 0; + public static final int FLAG_SHORTER = 1; public static String formatFileSize(Context context, long sizeBytes) { diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/util/ResUtil.java b/imagepicker/src/main/java/com/lzy/imagepicker/util/ResUtil.java index 6d61e87abec4e25c495288e0bc235c6b31e5767c..d74b87f1377d7f5c90b0cda93059bf6c54b9aaf4 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/util/ResUtil.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/util/ResUtil.java @@ -1,14 +1,8 @@ package com.lzy.imagepicker.util; -import ohos.aafwk.ability.Ability; -import ohos.agp.colors.RgbColor; import ohos.agp.components.AttrSet; -import ohos.agp.components.Component; import ohos.agp.components.element.*; import ohos.agp.components.element.Element; -import ohos.agp.render.Arc; -import ohos.agp.utils.Color; -import ohos.agp.window.service.Window; import ohos.app.Context; import ohos.global.resource.*; import ohos.media.image.ImageSource; @@ -16,16 +10,9 @@ import ohos.media.image.PixelMap; import java.io.IOException; import java.util.Optional; -import java.util.OptionalInt; public class ResUtil { - private static final String TAG = "ResUtil"; - - private static final String CITY_ID_ATTR = "cityId_"; - - private static final String STRING_ID_ATTR = "String_"; - private ResUtil() { } @@ -55,18 +42,6 @@ public class ResUtil { return path; } - /** - * get the new color - * - * @param context the context - * @param id the id - * @return the color - */ - public static Color getNewColor(Context context, int id) { - Color result = new Color(getColor(context, id)); - return result; - } - /** * get the color * @@ -93,43 +68,6 @@ public class ResUtil { return result; } - /** - * get the dimen value - * - * @param context the context - * @param id the id - * @return get the float dimen value - */ - public static float getDimen(Context context, int id) { - float result = 0; - if (context == null) { - - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - - return result; - } - try { - result = manager.getElement(id).getFloat(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * get the dimen value - * - * @param context the context - * @param id the id - * @return get the int dimen value - */ - public static int getIntDimen(Context context, int id) { - float value = getDimen(context, id); - return (int) (value >= 0 ? value + 0.5f : value - 0.5f); - } /** * get string @@ -163,99 +101,6 @@ public class ResUtil { return String.format(getString(context, id), format); } - - /** - * get boolean - * - * @param context the context - * @param id the boolean id - * @return boolean of the given id - */ - public static boolean getBoolean(Context context, int id) { - boolean result = false; - if (context == null) { - - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - - return result; - } - try { - result = manager.getElement(id).getBoolean(); - } catch (IOException | NotExistException | WrongTypeException e) { - return result; - } - return result; - } - - /* get the string array - * - * @param context the context - * @param id the string array idURLUtil - * @return the string array - */ - public static String[] getStringArray(Context context, int id) { - String[] result = null; - if (context == null) { - - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - - return result; - } - try { - result = manager.getElement(id).getStringArray(); - } catch (IOException | WrongTypeException | NotExistException e) { - return result; - } - return result; - } - - /** - * get the int array - * - * @param context the context - * @param id the int array - * @return the int array - */ - public static int[] getIntArray(Context context, int id) { - int[] result = null; - if (context == null) { - - return result; - } - ResourceManager manager = context.getResourceManager(); - if (manager == null) { - - return result; - } - try { - result = manager.getElement(id).getIntArray(); - } catch (IOException | NotExistException | WrongTypeException e) { - return result; - } - return result; - } - - /** - * get the vector drawable - * - * @param context the context - * @param id the drawable id - * @return the vector drawable - */ - public static VectorElement getVectorDrawable(Context context, int id) { - if (context == null) { - - return null; - } - return new VectorElement(context, id); - } - /** * get the pixel map * @@ -299,100 +144,6 @@ public class ResUtil { return ElementScatter.getInstance(context).parse(resId); } - public static Element getColorDrawable(int color) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - return drawable; - } - - - /** - * get the Element - * - * @param color the color - * @return the Element - */ - public static Element buildDrawableByColor(int color) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - return drawable; - } - - /** - * get the Element By ColorRadius - * - * @param color the color - * @param radius the radius - * @return the Element By ColorRadius - */ - public static Element buildDrawableByColorRadius(int color, float radius) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.RECTANGLE); - drawable.setRgbColor(RgbColor.fromArgbInt(color)); - drawable.setCornerRadius(radius); - return drawable; - } - - /** - * get the ShapeElement - * - * @param thickness the thickness - * @param inside the inside color - * @param border the border color - * @param startAngle the start angle - * @param sweepAngle the sweep angle - * @return the ShapeElement - */ - public static ShapeElement getCustomArcGradientDrawable(int thickness, Color inside, Color border, float startAngle, - float sweepAngle) { - ShapeElement drawable = new ShapeElement(); - drawable.setShape(ShapeElement.ARC); - drawable.setRgbColor(RgbColor.fromArgbInt(inside.getValue())); // keep it transparent for main(inner) part - drawable.setArc(new Arc(startAngle, sweepAngle, false)); - drawable.setStroke(thickness, RgbColor.fromArgbInt(border.getValue())); - return drawable; - } - - /** - * get res id by reflect - * - * @param resClass res class - * @param resName res name - * @return res id - */ - public static OptionalInt getResIdByReflect(Class resClass, String resName) { - return null; - } - - - /** - * get native city name - * - * @param context the context - * @param cityId cityId - * @return city name from cityId - */ - public static String getNativeCityName(Context context, String cityId) { - return null; - } - - /** - * find view by id - * - * @param view rootView - * @param id res id - * @param type - * @return view - */ - public static T findComponentById(Component view, int id) { - if (view == null) { - return null; - } - return (T) view.findComponentById(id); - } - public static int getColorValue(AttrSet attrSet, String name, int defaultValue) { try { int value = attrSet.getAttr(name).get().getColorValue().getValue(); diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/util/RotateGestureDetector.java b/imagepicker/src/main/java/com/lzy/imagepicker/util/RotateGestureDetector.java deleted file mode 100644 index 46f7d93198d01a9cf8db37ed95412ef936e1dc25..0000000000000000000000000000000000000000 --- a/imagepicker/src/main/java/com/lzy/imagepicker/util/RotateGestureDetector.java +++ /dev/null @@ -1,167 +0,0 @@ -package com.lzy.imagepicker.util; - -import ohos.multimodalinput.event.TouchEvent; - -/** - * @author Almer Thie (code.almeros.com) - * Copyright (c) 2013, Almer Thie (code.almeros.com) - *

- * All rights reserved. - *

- * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - *

- * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer - * in the documentation and/or other materials provided with the distribution. - *

- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, - * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, - * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY - * OF SUCH DAMAGE. - */ -public class RotateGestureDetector { - - private static final int INVALID_POINTER_INDEX = -1; - - private float fX, fY, sX, sY; - - private int mPointerIndex1, mPointerIndex2; - private float mAngle; - private boolean mIsFirstTouch; - - private OnRotationGestureListener mListener; - - public RotateGestureDetector(OnRotationGestureListener listener) { - mListener = listener; - mPointerIndex1 = INVALID_POINTER_INDEX; - mPointerIndex2 = INVALID_POINTER_INDEX; - } - - public float getAngle() { - return mAngle; - } - - public boolean onTouchEvent(TouchEvent event) { - switch (event.getAction()) { - case TouchEvent.PRIMARY_POINT_DOWN: - sX = event.getPointerPosition(0).getX(); - sY = event.getPointerPosition(0).getY(); - mPointerIndex1 = event.getPointerId(0); - break; - case TouchEvent.OTHER_POINT_DOWN: - fX = event.getPointerPosition(0).getX(); - fY = event.getPointerPosition(0).getY(); - mPointerIndex2 = event.getPointerId(event.getIndex()); - break; - case TouchEvent.POINT_MOVE: - if (mPointerIndex1 != INVALID_POINTER_INDEX && mPointerIndex2 != INVALID_POINTER_INDEX && event.getPointerCount() > mPointerIndex2) { - float nfX, nfY, nsX, nsY; - - nsX = event.getPointerPosition(mPointerIndex1).getX(); - nsY = event.getPointerPosition(mPointerIndex1).getY(); - nfX = event.getPointerPosition(mPointerIndex2).getX(); - nfY = event.getPointerPosition(mPointerIndex2).getY(); - - calculateAngleBetweenLines(fX, fY, sX, sY, nfX, nfY, nsX, nsY); - - if (mListener != null) { - mListener.onRotation(this); - } - if (Math.abs(fY - nfY) > 50 || Math.abs(sY - nsY) > 50){ - fX = nfX; - fY = nfY; - sX = nsX; - sY = nsY; - } - } - break; - case TouchEvent.PRIMARY_POINT_UP: - mPointerIndex1 = INVALID_POINTER_INDEX; - break; - case TouchEvent.OTHER_POINT_UP: - mPointerIndex2 = INVALID_POINTER_INDEX; - break; - } - return true; - } - - private void calculateAngleBetweenLines(float fx1, float fy1, float fx2, float fy2, - float sx1, float sy1, float sx2, float sy2) { - calculateAngleDelta( - (float) Math.toDegrees((float) Math.atan2((fy1 - fy2), (fx1 - fx2))), - (float) Math.toDegrees((float) Math.atan2((sy1 - sy2), (sx1 - sx2)))); - - calculateAngleDelta2(sx1, sy1, sx2, sy2); - } - - private void calculateAngleDelta(float angleFrom, float angleTo) { -// mAngle = angleTo % 360.0f - angleFrom % 360.0f; -// if (mAngle < -180.0f) { -// mAngle += 360.0f; -// } else if (mAngle > 180.0f) { -// mAngle -= 360.0f; -// } - } - - private void calculateAngleDelta2(float nfX, float nfY, float nsX, float nsY) { - //顺时针旋转 - if (sX > fX){//第一个手指在右,第二个手指在左 - if ((fY > nfY && sY < nsY)) { - if (Math.abs(fY - nfY) > 50 || Math.abs(sY - nsY) > 50){ - if (mAngle == 360){ - mAngle = 0; - } - mAngle = mAngle + 10; - } - } - } - if (sX < fX){//第一个手指在左,第二个手指在右 - if ((fY < nfY && sY > nsY)) { - if (Math.abs(fY - nfY) > 50 || Math.abs(sY - nsY) > 50){ - if (mAngle == 360){ - mAngle = 0; - } - mAngle = mAngle + 10; - } - } - } - - //逆时针旋转 - if (sX > fX){//第一个手指在右,第二个手指在左 - if ((fY < nfY && sY > nsY)) { - if (Math.abs(fY - nfY) > 50 || Math.abs(sY - nsY) > 50){ - if (mAngle == -360){ - mAngle = 0; - } - mAngle = mAngle - 10; - } - } - } - if (sX < fX){//第一个手指在左,第二个手指在右 - if ((fY > nfY && sY < nsY)) { - if (Math.abs(fY - nfY) > 50 || Math.abs(sY - nsY) > 50){ - if (mAngle == -360){ - mAngle = 0; - } - mAngle = mAngle - 10; - } - } - } - } - - public static class SimpleOnRotationGestureListener implements OnRotationGestureListener { - - @Override - public boolean onRotation(RotateGestureDetector rotationDetector) { - return false; - } - } - - public interface OnRotationGestureListener { - - boolean onRotation(RotateGestureDetector rotationDetector); - } -} diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/util/Utils.java b/imagepicker/src/main/java/com/lzy/imagepicker/util/Utils.java index 75d6fff0c8701673a92c37e92a86133c93f684a5..a354f8e076b008cab82bd0d38bffae8943cc8d69 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/util/Utils.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/util/Utils.java @@ -1,12 +1,9 @@ package com.lzy.imagepicker.util; import ohos.aafwk.ability.Ability; -import ohos.aafwk.ability.AbilitySlice; import ohos.agp.window.service.Display; import ohos.agp.window.service.DisplayManager; import ohos.app.Context; -import ohos.data.usage.DataUsage; -import ohos.data.usage.MountState; /** * ================================================ @@ -18,10 +15,6 @@ import ohos.data.usage.MountState; * ================================================ */ public class Utils { - - /** -// * 获得状态栏的高度 -// */ // public static int getStatusHeight(Context context) { // int statusHeight = -1; // try { @@ -48,66 +41,11 @@ public class Utils { int screenWidth = display.getAttributes().width; int densityDpi = display.getAttributes().densityDpi; int cols = screenWidth / densityDpi; - cols = cols < 3 ? 3 : cols; + cols = Math.max(cols, 3); int columnSpace = (int) (2 * display.getAttributes().densityPixels); return (screenWidth - columnSpace * (cols - 1)) / cols; } - /** - * 判断SDCard是否可用 - * @return 是否有sd卡 - */ - public static boolean existSDCard() { - return DataUsage.getDiskMountedStatus().equals(MountState.DISK_MOUNTED); - } - -// /** -// * 获取手机大小(分辨率) -// */ -// public static DisplayMetrics getScreenPix(Activity ability) { -// DisplayMetrics displaysMetrics = new DisplayMetrics(); -// ability.getWindowManager().getDefaultDisplay().getMetrics(displaysMetrics); -// return displaysMetrics; -// } - - /** - * vp转px - */ -// public static int vp2px(Context context, float vpVal) { -// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, vpVal, context.getResources().getDisplayMetrics()); -// } - - /** - * 判断手机是否含有虚拟按键 99% - */ -// public static boolean hasVirtualNavigationBar(Context context) { -// boolean hasSoftwareKeys = true; -// -// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { -// Display d = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); -// -// DisplayMetrics realDisplayMetrics = new DisplayMetrics(); -// d.getRealMetrics(realDisplayMetrics); -// -// int realHeight = realDisplayMetrics.heightPixels; -// int realWidth = realDisplayMetrics.widthPixels; -// -// DisplayMetrics displayMetrics = new DisplayMetrics(); -// d.getMetrics(displayMetrics); -// -// int displayHeight = displayMetrics.heightPixels; -// int displayWidth = displayMetrics.widthPixels; -// -// hasSoftwareKeys = (realWidth - displayWidth) > 0 || (realHeight - displayHeight) > 0; -// } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { -// boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey(); -// boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK); -// hasSoftwareKeys = !hasMenuKey && !hasBackKey; -// } -// -// return hasSoftwareKeys; -// } - /** * 获取导航栏高度,有些没有虚拟导航栏的手机也能获取到,建议先判断是否有虚拟按键 * @param mContext 上下文对象 @@ -116,16 +54,11 @@ public class Utils { */ public static int vp2px(int vp, Context mContext) { - return (int)(mContext.getResourceManager().getDeviceCapability().screenDensity / 160 * vp); + return mContext.getResourceManager().getDeviceCapability().screenDensity / 160 * vp; } - public static int[] getScreenSize(Context context) { - DisplayManager displayManager = DisplayManager.getInstance(); - Display display = displayManager.getDefaultDisplay(context).get(); - - int screenWidth = display.getAttributes().width; - int screenHeith = display.getAttributes().height; - return new int[]{screenWidth, screenHeith}; + public static void getScreenSize(Context context) { + System.out.println(context); } } diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/view/CropImageView.java b/imagepicker/src/main/java/com/lzy/imagepicker/view/CropImageView.java index 7f53dc460716114079901d87271a3e8eaa3d19b7..213e1674171ed05f98ca672233a72f5ec6b7e787 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/view/CropImageView.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/view/CropImageView.java @@ -1,14 +1,11 @@ package com.lzy.imagepicker.view; - -import com.lzy.imagepicker.ResourceTable; import com.lzy.imagepicker.util.ResUtil; import com.lzy.imagepicker.util.Utils; import ohos.agp.components.AttrSet; import ohos.agp.components.Component; import ohos.agp.components.Image; import ohos.agp.components.element.Element; -import ohos.agp.components.element.PixelMapElement; import ohos.agp.render.*; import ohos.agp.utils.Color; import ohos.agp.utils.Matrix; @@ -24,16 +21,13 @@ import ohos.eventhandler.InnerEvent; import ohos.media.image.ImagePacker; import ohos.media.image.ImageSource; import ohos.media.image.PixelMap; -import ohos.media.image.common.ImageFormat; import ohos.media.image.common.PixelFormat; import ohos.media.image.common.Rect; import ohos.multimodalinput.event.TouchEvent; -import ohos.utils.net.Uri; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; -import java.io.OutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; @@ -60,25 +54,21 @@ public class CropImageView extends Image { RECTANGLE, CIRCLE } - private Style[] styles = {Style.RECTANGLE, Style.CIRCLE}; - private int mMaskColor = 0x80000000; //暗色 private int mBorderColor = 0xAA808080; //焦点框的边框颜色 private int mBorderWidth = 1; //焦点边框的宽度(画笔宽度) private int mFocusWidth = 250; //焦点框的宽度 private int mFocusHeight = 250; //焦点框的高度 - private int mDefaultStyleIndex = 0; //默认焦点框的形状 + public int mDefaultStyleIndex = 0; //默认焦点框的形状 - private Style mStyle = styles[mDefaultStyleIndex]; - private Paint mBorderPaint = new Paint(); - private Path mFocusPath = new Path(); - private RectFloat mFocusRect = new RectFloat(); + private Style mStyle; + private final Paint mBorderPaint = new Paint(); + private final Path mFocusPath = new Path(); + private final RectFloat mFocusRect = new RectFloat(); /******************************** 图片缩放位移控制的参数 ************************************/ private static final float MAX_SCALE = 4.0f; //最大缩放比,图片缩放后的大小与中间选中区域的比值 private static final int NONE = 0; // 初始化 - private static final int DRAG = 1; // 拖拽 - private static final int ZOOM = 2; // 缩放 private static final int ZOOM_OR_ROTATE = 4; // 缩放或旋转 private static final int SAVE_SUCCESS = 1001; // 缩放或旋转 @@ -88,24 +78,19 @@ public class CropImageView extends Image { private int mImageHeight; private int mRotatedImageWidth; private int mRotatedImageHeight; - private Matrix matrix = new Matrix(); //图片变换的matrix - private Matrix savedMatrix = new Matrix(); //开始变幻的时候,图片的matrix - private Point pA = new Point(); //第一个手指按下点的坐标 - private Point pB = new Point(); //第二个手指按下点的坐标 - private Point midPoint = new Point(); //两个手指的中间点 - private Point doubleClickPos = new Point(); //双击图片的时候,双击点的坐标 + private final Matrix matrix = new Matrix(); //图片变换的matrix + private final Matrix savedMatrix = new Matrix(); //开始变幻的时候,图片的matrix + private final Point pA = new Point(); //第一个手指按下点的坐标 + private final Point pB = new Point(); //第二个手指按下点的坐标 + private final Point midPoint = new Point(); //两个手指的中间点 private Point mFocusMidPoint = new Point(); //中间View的中间点 private int mode = NONE; //初始的模式 - private long doubleClickTime = 0; //第二次双击的时间 - private double rotation = 0; //手指旋转的角度,不是90的整数倍,可能为任意值,需要转换成level private float oldDist = 1; //双指第一次的距离 - private int sumRotateLevel = 0; //旋转的角度,90的整数倍 private float mMaxScale = MAX_SCALE;//程序根据不同图片的大小,动态得到的最大缩放比 - private boolean isInited = false; //是否经过了 onSizeChanged 初始化 + private final boolean isInited; //是否经过了 onSizeChanged 初始化 private boolean mSaving = false; //是否正在保存 - private static EventHandler mHandler = new InnerHandler(); + private static final EventHandler mHandler = new InnerHandler(); private PixelMap pixelMap; - private Canvas canvas; private int mPointerIndex1, mPointerIndex2; public CropImageView(Context context) { @@ -134,6 +119,7 @@ public class CropImageView extends Image { mFocusHeight = ResUtil.getDimensionValue(attrs, "cropFocusHeight", mFocusHeight); mDefaultStyleIndex = ResUtil.getIntValue(attrs, "cropStyle", mDefaultStyleIndex); + Style[] styles = {Style.RECTANGLE, Style.CIRCLE}; mStyle = styles[mDefaultStyleIndex]; // a.recycle(); @@ -142,47 +128,41 @@ public class CropImageView extends Image { //只允许图片为当前的缩放模式 // setScaleType(ScaleType.MATRIX); - setLayoutRefreshedListener(new LayoutRefreshedListener() { - @Override - public void onRefreshed(Component component) { - initImage(pixelMap); - component.addDrawTask(new DrawTask() { - @Override - public void onDraw(Component component, Canvas canvas) { - canvas.concat(matrix); - if (Style.RECTANGLE == mStyle) { - Optional - display = DisplayManager.getInstance().getDefaultDisplay(getContext()); - DisplayAttributes displayAttributes = display.get().getAttributes(); - - mFocusPath.addRect(mFocusRect, Path.Direction.COUNTER_CLOCK_WISE); - canvas.save(); - canvas.clipRect(new RectFloat(0, 0, displayAttributes.width, displayAttributes.height)); - canvas.clipPath(mFocusPath, Canvas.ClipOp.DIFFERENCE); - canvas.drawColor(mMaskColor, Canvas.PorterDuffMode.DST_IN); - canvas.restore(); - } else if (Style.CIRCLE == mStyle) { - float radius = Math.min((mFocusRect.right - mFocusRect.left) / 2, (mFocusRect.bottom - mFocusRect.top) / 2); - - mFocusPath.addCircle(mFocusMidPoint.getPointX(), mFocusMidPoint.getPointY(), radius, Path.Direction.COUNTER_CLOCK_WISE); - - canvas.save(); - canvas.clipRect(new RectFloat(0, 0, getWidth(), getHeight())); - - canvas.clipPath(mFocusPath, Canvas.ClipOp.DIFFERENCE); - canvas.drawColor(mMaskColor, Canvas.PorterDuffMode.DST_IN); - canvas.restore(); - } - mBorderPaint.setColor(new Color(mBorderColor)); - mBorderPaint.setStyle(Paint.Style.STROKE_STYLE); - mBorderPaint.setStrokeWidth(mBorderWidth); - - mBorderPaint.setAntiAlias(true); - canvas.drawPath(mFocusPath, mBorderPaint); - mFocusPath.reset(); - } - }); - } + setLayoutRefreshedListener(component -> { + initImage(pixelMap); + component.addDrawTask((component1, canvas) -> { + canvas.concat(matrix); + if (Style.RECTANGLE == mStyle) { + Optional + display = DisplayManager.getInstance().getDefaultDisplay(getContext()); + DisplayAttributes displayAttributes = display.get().getAttributes(); + + mFocusPath.addRect(mFocusRect, Path.Direction.COUNTER_CLOCK_WISE); + canvas.save(); + canvas.clipRect(new RectFloat(0, 0, displayAttributes.width, displayAttributes.height)); + canvas.clipPath(mFocusPath, Canvas.ClipOp.DIFFERENCE); + canvas.drawColor(mMaskColor, Canvas.PorterDuffMode.DST_IN); + canvas.restore(); + } else if (Style.CIRCLE == mStyle) { + float radius = Math.min((mFocusRect.right - mFocusRect.left) / 2, (mFocusRect.bottom - mFocusRect.top) / 2); + + mFocusPath.addCircle(mFocusMidPoint.getPointX(), mFocusMidPoint.getPointY(), radius, Path.Direction.COUNTER_CLOCK_WISE); + + canvas.save(); + canvas.clipRect(new RectFloat(0, 0, getWidth(), getHeight())); + + canvas.clipPath(mFocusPath, Canvas.ClipOp.DIFFERENCE); + canvas.drawColor(mMaskColor, Canvas.PorterDuffMode.DST_IN); + canvas.restore(); + } + mBorderPaint.setColor(new Color(mBorderColor)); + mBorderPaint.setStyle(Paint.Style.STROKE_STYLE); + mBorderPaint.setStrokeWidth(mBorderWidth); + + mBorderPaint.setAntiAlias(true); + canvas.drawPath(mFocusPath, mBorderPaint); + mFocusPath.reset(); + }); }); } @@ -254,7 +234,7 @@ public class CropImageView extends Image { //确定最终的缩放比例,在适配焦点框的前提下适配显示图片的ImageView, //方案:首先满足适配焦点框,如果还能适配显示图片的ImageView,则适配它,即取缩放比例的最大值。 //采取这种方案的原因:有可能图片很长或者很高,适配了ImageView的时候可能会宽/高已经小于焦点框的宽/高 - float scale = fitViewScale > fitFocusScale ? fitViewScale : fitFocusScale; + float scale = Math.max(fitViewScale, fitFocusScale); //图像中点为中心进行缩放 matrix.setScale(scale, scale, mImageWidth / 2, mImageHeight / 2); @@ -271,63 +251,61 @@ public class CropImageView extends Image { if (getTouchEventListener() == null) - setTouchEventListener(new TouchEventListener() { - @Override - public boolean onTouchEvent(Component component, TouchEvent event) { + setTouchEventListener((component, event) -> { // if (mSaving || null == getImageElement()) { // return super.onTouchEvent(event); // } - switch (event.getAction()) { - case TouchEvent.PRIMARY_POINT_DOWN: //第一个点按下 - savedMatrix.setMatrix(matrix); //以后每次需要变换的时候,以现在的状态为基础进行变换 - pA.modify(event.getPointerPosition(0).getX(), event.getPointerPosition(0).getY()); - pB.modify(event.getPointerPosition(0).getX(), event.getPointerPosition(0).getY()); - mPointerIndex1 = event.getPointerId(0); + switch (event.getAction()) { + case TouchEvent.PRIMARY_POINT_DOWN: //第一个点按下 + savedMatrix.setMatrix(matrix); //以后每次需要变换的时候,以现在的状态为基础进行变换 + pA.modify(event.getPointerPosition(0).getX(), event.getPointerPosition(0).getY()); + pB.modify(event.getPointerPosition(0).getX(), event.getPointerPosition(0).getY()); + mPointerIndex1 = event.getPointerId(0); // mode = DRAG; - break; - case TouchEvent.OTHER_POINT_DOWN: //第二个点按下 - int ind = event.getIndex(); - System.out.println(ind); - if (event.getIndex() > 1) break; - pA.modify(event.getPointerPosition(0).getX(), event.getPointerPosition(0).getY()); - pB.modify(event.getPointerPosition(1).getX(), event.getPointerPosition(1).getY()); - midPoint.modify((pA.getPointX() + pB.getPointX()) / 2, (pA.getPointY() + pB.getPointY()) / 2); - mPointerIndex2 = event.getPointerId(event.getIndex()); - - oldDist = spacing(pA, pB); - savedMatrix.setMatrix(matrix); //以后每次需要变换的时候,以现在的状态为基础进行变换 - if (oldDist > 10f) mode = ZOOM_OR_ROTATE;//两点之间的距离大于10才有效 - break; - case TouchEvent.POINT_MOVE: - if (mode == ZOOM_OR_ROTATE) { - int index = event.getIndex(); - System.out.println(index); - float nfX, nfY, nsX, nsY; - - nsX = event.getPointerPosition(mPointerIndex1).getX(); - nsY = event.getPointerPosition(mPointerIndex1).getY(); - int count = event.getPointerCount(); - System.out.println("count" + count); - if (count == 2) { - nfX = event.getPointerPosition(mPointerIndex2).getX(); - nfY = event.getPointerPosition(mPointerIndex2).getY(); - - float newDist = spacing(nsX, nsY, nfX, nfY); - if (newDist > 10f) { - matrix.setMatrix(savedMatrix); - // 这里之所以用 maxPostScale 矫正一下,主要是防止缩放到最大时,继续缩放图片会产生位移 - float tScale = Math.min(newDist / oldDist, maxPostScale()); - if (tScale != 0) { - matrix.postScale(tScale, tScale, midPoint.getPointX(), midPoint.getPointY()); - fixScale(); - fixTranslation(); + break; + case TouchEvent.OTHER_POINT_DOWN: //第二个点按下 + int ind = event.getIndex(); + System.out.println(ind); + if (event.getIndex() > 1) break; + pA.modify(event.getPointerPosition(0).getX(), event.getPointerPosition(0).getY()); + pB.modify(event.getPointerPosition(1).getX(), event.getPointerPosition(1).getY()); + midPoint.modify((pA.getPointX() + pB.getPointX()) / 2, (pA.getPointY() + pB.getPointY()) / 2); + mPointerIndex2 = event.getPointerId(event.getIndex()); + + oldDist = spacing(pA, pB); + savedMatrix.setMatrix(matrix); //以后每次需要变换的时候,以现在的状态为基础进行变换 + if (oldDist > 10f) mode = ZOOM_OR_ROTATE;//两点之间的距离大于10才有效 + break; + case TouchEvent.POINT_MOVE: + if (mode == ZOOM_OR_ROTATE) { + int index = event.getIndex(); + System.out.println(index); + float nfX, nfY, nsX, nsY; + + nsX = event.getPointerPosition(mPointerIndex1).getX(); + nsY = event.getPointerPosition(mPointerIndex1).getY(); + int count = event.getPointerCount(); + System.out.println("count" + count); + if (count == 2) { + nfX = event.getPointerPosition(mPointerIndex2).getX(); + nfY = event.getPointerPosition(mPointerIndex2).getY(); + + float newDist = spacing(nsX, nsY, nfX, nfY); + if (newDist > 10f) { + matrix.setMatrix(savedMatrix); + // 这里之所以用 maxPostScale 矫正一下,主要是防止缩放到最大时,继续缩放图片会产生位移 + float tScale = Math.min(newDist / oldDist, maxPostScale()); + if (tScale != 0) { + matrix.postScale(tScale, tScale, midPoint.getPointX(), midPoint.getPointY()); + fixScale(); + fixTranslation(); // setImageMatrix(matrix); - } } } } - break; - case TouchEvent.PRIMARY_POINT_UP: + } + break; + case TouchEvent.PRIMARY_POINT_UP: // if (mode == DRAG) { // if (spacing(pA, pB) < 50) { // long now = System.currentTimeMillis(); @@ -340,13 +318,12 @@ public class CropImageView extends Image { // } // } // mode = NONE; - break; - } - //解决部分机型无法拖动的问题 - invalidate(); -// ViewCompat.postInvalidateOnAnimation(this); - return true; + break; } + //解决部分机型无法拖动的问题 + invalidate(); +// ViewCompat.postInvalidateOnAnimation(this); + return true; }); } @@ -365,9 +342,9 @@ public class CropImageView extends Image { float scaleX = (float) min_width / bitmapWidth; float scaleY = (float) min_height / bitmapHeight; if (isMinScale) { - scale = scaleX > scaleY ? scaleX : scaleY; + scale = Math.max(scaleX, scaleY); } else { - scale = scaleX < scaleY ? scaleX : scaleY; + scale = Math.min(scaleX, scaleY); } return scale; } @@ -451,28 +428,6 @@ public class CropImageView extends Image { return spacing(pA.getPointX(), pA.getPointY(), pB.getPointX(), pB.getPointY()); } - /** - * 双击触发的方法 - * @param x - * @param y - */ - private void doubleClick(float x, float y) { - float p[] = new float[9]; - matrix.getElements(p); - float curScale = Math.abs(p[0]) + Math.abs(p[1]); - float minScale = getScale(mRotatedImageWidth, mRotatedImageHeight, mFocusWidth, mFocusHeight, true); - if (curScale < mMaxScale) { - //每次双击的时候,缩放加 minScale - float toScale = Math.min(curScale + minScale, mMaxScale) / curScale; - matrix.postScale(toScale, toScale, x, y); - } else { - float toScale = minScale / curScale; - matrix.postScale(toScale, toScale, x, y); - fixTranslation(); - } -// setImageMatrix(matrix); - } - /** * 获取裁剪过的PixelMap * @param expectWidth 期望的宽度 @@ -484,6 +439,8 @@ public class CropImageView extends Image { if (expectWidth <= 0 || exceptHeight < 0) return null; // PixelMap srcBitmap = getPixelMap(); + //旋转的角度,90的整数倍 + int sumRotateLevel = 0; pixelMap = rotate(pixelMap, sumRotateLevel * 90); //最好用level,因为角度可能不是90的整数 return makeCropBitmap(pixelMap, mFocusRect, getImageMatrixRect(), expectWidth, exceptHeight, isSaveRectangle); @@ -605,8 +562,7 @@ public class CropImageView extends Image { final PixelMap croppedImage = getCropBitmap(expectWidth, exceptHeight, isSaveRectangle); ImagePacker.PackingOptions options = new ImagePacker.PackingOptions(); options.format = "image/jpeg"; - File saveFile = createFile(folder, "IMG_", ".jpg"); - final File finalSaveFile = saveFile; + final File finalSaveFile = createFile(folder, "IMG_", ".jpg"); new Thread() { @Override public void run() { @@ -630,6 +586,9 @@ public class CropImageView extends Image { File nomedia = new File(folder, ".nomedia"); //在当前文件夹底下创建一个 .nomedia 文件 if (!nomedia.exists()){ boolean create = nomedia.createNewFile(); + if(create){ + System.out.println(); + } } } catch (IOException e) { return new File(folder, "filename"); @@ -654,8 +613,8 @@ public class CropImageView extends Image { if (outputStream != null) { outputFormat.quality = 90; imagePacker.initializePacking(outputStream, outputFormat); - boolean result = imagePacker.addImage(croppedImage); - long dataSize = imagePacker.finalizePacking(); + imagePacker.addImage(croppedImage); + imagePacker.finalizePacking(); // croppedImage.compress(outputFormat, 90, outputStream); } @@ -707,20 +666,12 @@ public class CropImageView extends Image { /** * 设置图片保存成功的回调 - * @param listener + * @param listener listener */ public void setOnBitmapSaveCompleteListener(OnBitmapSaveCompleteListener listener) { mListener = listener; } - /** - * 返回焦点框宽度 - * @return 焦点框宽度 - */ - public int getFocusWidth() { - return mFocusWidth; - } - /** * 设置焦点框的宽度 * @param width 焦点宽度 @@ -730,14 +681,6 @@ public class CropImageView extends Image { initImage(this.pixelMap); } - /** - * 获取焦点框的高度 - * @return 焦点框高度 - */ - public int getFocusHeight() { - return mFocusHeight; - } - /** * 设置焦点框的高度 * @param height 焦点框高度 @@ -747,57 +690,6 @@ public class CropImageView extends Image { initImage(this.pixelMap); } - /** - * 返回阴影颜色 - * @return maskColor 阴影颜色 - */ - public int getMaskColor() { - return mMaskColor; - } - - /** - * 设置阴影颜色 - * @param color 阴影颜色 - */ - public void setMaskColor(int color) { - mMaskColor = color; - invalidate(); - } - - /** - * 返回焦点框边框颜色 - * @return focusColor 焦点框边框颜色 - */ - public int getFocusColor() { - return mBorderColor; - } - - /** - * 设置焦点框边框颜色 - * @param color border color - */ - public void setBorderColor(int color) { - mBorderColor = color; - invalidate(); - } - - /** - * 返回焦点框边框绘制宽度 - * @return borderWidth - */ - public float getBorderWidth() { - return mBorderWidth; - } - - /** - * 设置焦点边框宽度 - * @param width borderWidth - */ - public void setBorderWidth(int width) { - mBorderWidth = width; - invalidate(); - } - /** * 设置焦点框的形状 * @param style focusStyle @@ -806,12 +698,4 @@ public class CropImageView extends Image { this.mStyle = style; invalidate(); } - - /** - * 获取焦点框的形状 - * @return focusStyle - */ - public Style getFocusStyle() { - return mStyle; - } } \ No newline at end of file diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/view/FolderPopUpWindow.java b/imagepicker/src/main/java/com/lzy/imagepicker/view/FolderPopUpWindow.java index 5943011dc45d4d904d46b5c38fe55c557ebf7588..2d3a57b0d9db3378119f820d828c314adf52c343 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/view/FolderPopUpWindow.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/view/FolderPopUpWindow.java @@ -1,7 +1,6 @@ package com.lzy.imagepicker.view; -import com.lzy.imagepicker.ResourceTable; import com.lzy.imagepicker.ResourceTable; import ohos.agp.animation.Animator; import ohos.agp.animation.AnimatorGroup; @@ -26,7 +25,7 @@ import java.lang.reflect.Method; */ public class FolderPopUpWindow extends PopupDialog implements Component.ClickedListener, BaseDialog.DialogListener { - private ListContainer listView; + private final ListContainer listView; private OnItemClickListener onItemClickListener; private final Component masker; private final Component marginView; @@ -59,7 +58,7 @@ public class FolderPopUpWindow extends PopupDialog implements Component.ClickedL int maxHeight = component.getHeight() * 5 / 8; int realHeight = listView.getHeight(); ComponentContainer.LayoutConfig listParams = listView.getLayoutConfig(); - listParams.height = realHeight > maxHeight ? maxHeight : realHeight; + listParams.height = Math.min(realHeight, maxHeight); listView.setLayoutConfig(listParams); DirectionalLayout.LayoutConfig marginParams = (DirectionalLayout.LayoutConfig) marginView.getLayoutConfig(); marginParams.height = marginPx; @@ -68,12 +67,8 @@ public class FolderPopUpWindow extends PopupDialog implements Component.ClickedL } }); - listView.setItemClickedListener(new ListContainer.ItemClickedListener() { - @Override - public void onItemClicked(ListContainer listContainer, Component component, int position, long l) { - if (onItemClickListener != null) onItemClickListener.onItemClick(listContainer, component, position, l); - } - + listView.setItemClickedListener((listContainer, component1, position, l) -> { + if (onItemClickListener != null) onItemClickListener.onItemClick(listContainer, component1, position, l); }); } diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/view/SuperCheckBox.java b/imagepicker/src/main/java/com/lzy/imagepicker/view/SuperCheckBox.java index 75f7b46ce4109414987985329b7561263da32392..3e27730f3bf75c58e5c416d0b97a2d92bc16bb7c 100644 --- a/imagepicker/src/main/java/com/lzy/imagepicker/view/SuperCheckBox.java +++ b/imagepicker/src/main/java/com/lzy/imagepicker/view/SuperCheckBox.java @@ -16,22 +16,10 @@ import ohos.media.audio.SoundPlayer; */ public class SuperCheckBox extends Checkbox { - private Context context; SoundPlayer soundPlayer = new SoundPlayer(); - public SuperCheckBox(Context context) { - super(context); - this.context = context; - } - public SuperCheckBox(Context context, AttrSet attrs) { super(context, attrs); - this.context = context; - } - - public SuperCheckBox(Context context, AttrSet attrs, String styleName) { - super(context, attrs, null); - this.context = context; } @Override diff --git a/imagepicker/src/main/java/com/lzy/imagepicker/view/ViewPagerFixed.java b/imagepicker/src/main/java/com/lzy/imagepicker/view/ViewPagerFixed.java deleted file mode 100644 index 0da6de593162552ab6bc9d10dc58b2b33d8ed9d2..0000000000000000000000000000000000000000 --- a/imagepicker/src/main/java/com/lzy/imagepicker/view/ViewPagerFixed.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.lzy.imagepicker.view; - -import ohos.agp.components.AttrSet; -import ohos.agp.components.PageSlider; -import ohos.app.Context; - -/** - * ================================================ - * 作 者:jeasonlzy(廖子尧 Github地址:https://github.com/jeasonlzy0216 - * 版 本:1.0 - * 创建日期:2016/5/19 - * 描 述:修复图片在ViewPager控件中缩放报错的BUG - * 修订历史: - * ================================================ - */ -public class ViewPagerFixed extends PageSlider { - - public ViewPagerFixed(Context context) { - super(context); - } - - public ViewPagerFixed(Context context, AttrSet attrs) { - super(context, attrs); - } - -// @Override -// public boolean onTouchEvent(TouchEvent ev) { -// try { -// return super.onTouchEvent(ev); -// } catch (IllegalArgumentException ex) { -// ex.printStackTrace(); -// } -// return false; -// } - -// @Override -// public boolean onInterceptTouchEvent(TouchEvent ev) { -// try { -// return super.onInterceptTouchEvent(ev); -// } catch (IllegalArgumentException ex) { -// ex.printStackTrace(); -// } -// return false; -// } -} diff --git a/ucrop/src/main/java/com/yalantis/ucrop/callback/BitmapCropCallback.java b/ucrop/src/main/java/com/yalantis/ucrop/callback/BitmapCropCallback.java index 705cc966d0d8ced16a9b732b3b1927480d61fd30..3177d1877baa99f491e4c3cb1ed1cacfe5eac4c2 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/callback/BitmapCropCallback.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/callback/BitmapCropCallback.java @@ -5,8 +5,6 @@ import ohos.utils.net.Uri; public interface BitmapCropCallback { - void onBitmapCropped( Uri resultUri, int offsetX, int offsetY, int imageWidth, int imageHeight); - void onCropFailure( Throwable t); } \ No newline at end of file diff --git a/ucrop/src/main/java/com/yalantis/ucrop/model/AspectRatio.java b/ucrop/src/main/java/com/yalantis/ucrop/model/AspectRatio.java deleted file mode 100644 index c21d6c681540a16b008944b046f5425c41b3d701..0000000000000000000000000000000000000000 --- a/ucrop/src/main/java/com/yalantis/ucrop/model/AspectRatio.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.yalantis.ucrop.model; - - -import ohos.utils.Parcel; - -import ohos.utils.Sequenceable; - - -/** - * Created by Oleksii Shliama [https://github.com/shliama] on 6/24/16. - */ -public class AspectRatio implements Sequenceable { - - - private final String mAspectRatioTitle; - private final float mAspectRatioX; - private final float mAspectRatioY; - - public AspectRatio( String aspectRatioTitle, float aspectRatioX, float aspectRatioY) { - mAspectRatioTitle = aspectRatioTitle; - mAspectRatioX = aspectRatioX; - mAspectRatioY = aspectRatioY; - } - - protected AspectRatio(Parcel in) { - mAspectRatioTitle = in.readString(); - mAspectRatioX = in.readFloat(); - mAspectRatioY = in.readFloat(); - } - - @Override - public boolean marshalling(Parcel dest) { - dest.writeString(mAspectRatioTitle); - dest.writeFloat(mAspectRatioX); - dest.writeFloat(mAspectRatioY); - return false; - } - - @Override - public boolean unmarshalling(Parcel parcel) { - return false; - } - - - public static final Producer CREATOR = new Producer() { - @Override - public AspectRatio createFromParcel(Parcel in) { - return new AspectRatio(in); - } - - - public AspectRatio[] newArray(int size) { - return new AspectRatio[size]; - } - }; - - - public String getAspectRatioTitle() { - return mAspectRatioTitle; - } - - public float getAspectRatioX() { - return mAspectRatioX; - } - - public float getAspectRatioY() { - return mAspectRatioY; - } - - -} diff --git a/ucrop/src/main/java/com/yalantis/ucrop/model/CropParameters.java b/ucrop/src/main/java/com/yalantis/ucrop/model/CropParameters.java index 53bd0a450d576ed1e87877a21c9f80b79adf9b41..8aa111c43fead64714ba60483af0933cce31081b 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/model/CropParameters.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/model/CropParameters.java @@ -7,12 +7,13 @@ package com.yalantis.ucrop.model; */ public class CropParameters { - private int mMaxResultImageSizeX, mMaxResultImageSizeY; + private final int mMaxResultImageSizeX; + private final int mMaxResultImageSizeY; - private String mCompressFormat; - private int mCompressQuality; - private String mImageInputPath, mImageOutputPath; - private ExifInfo mExifInfo; + private final String mCompressFormat; + private final int mCompressQuality; + private final String mImageInputPath, mImageOutputPath; + private final ExifInfo mExifInfo; //修改compressFormat类型为String public CropParameters(int maxResultImageSizeX, int maxResultImageSizeY, diff --git a/ucrop/src/main/java/com/yalantis/ucrop/model/ExifInfo.java b/ucrop/src/main/java/com/yalantis/ucrop/model/ExifInfo.java index 96da038ab9f445c03582705e7255768e9d889356..803019c4bab5e33f39fd9f1daee89e6cddb1e5c3 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/model/ExifInfo.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/model/ExifInfo.java @@ -5,9 +5,9 @@ package com.yalantis.ucrop.model; */ public class ExifInfo { - private int mExifOrientation; - private int mExifDegrees; - private int mExifTranslation; + private final int mExifOrientation; + private final int mExifDegrees; + private final int mExifTranslation; public ExifInfo(int exifOrientation, int exifDegrees, int exifTranslation) { mExifOrientation = exifOrientation; @@ -15,30 +15,6 @@ public class ExifInfo { mExifTranslation = exifTranslation; } - public int getExifOrientation() { - return mExifOrientation; - } - - public int getExifDegrees() { - return mExifDegrees; - } - - public int getExifTranslation() { - return mExifTranslation; - } - - public void setExifOrientation(int exifOrientation) { - mExifOrientation = exifOrientation; - } - - public void setExifDegrees(int exifDegrees) { - mExifDegrees = exifDegrees; - } - - public void setExifTranslation(int exifTranslation) { - mExifTranslation = exifTranslation; - } - @Override public boolean equals(Object o) { if (this == o) return true; diff --git a/ucrop/src/main/java/com/yalantis/ucrop/model/ImageState.java b/ucrop/src/main/java/com/yalantis/ucrop/model/ImageState.java index fdce0572e4579fb187806c91e05ca8aa42198480..7aadbf906f43230db25aa3ea3b7bfba26374b144 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/model/ImageState.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/model/ImageState.java @@ -8,10 +8,10 @@ import ohos.agp.utils.RectFloat; */ public class ImageState { - private RectFloat mCropRect; - private RectFloat mCurrentImageRect; + private final RectFloat mCropRect; + private final RectFloat mCurrentImageRect; - private float mCurrentScale, mCurrentAngle; + private final float mCurrentScale, mCurrentAngle; public ImageState(RectFloat cropRect, RectFloat currentImageRect, float currentScale, float currentAngle) { mCropRect = cropRect; diff --git a/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapCropTask.java b/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapCropTask.java index e072c6d6901e8aa039ed2de39cdfed2cb7de007d..372314f36ef5637bc919ce184cd2efec35ccf174 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapCropTask.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapCropTask.java @@ -32,7 +32,6 @@ import ohos.utils.net.Uri; import com.yalantis.ucrop.callback.BitmapCropCallback; import com.yalantis.ucrop.model.CropParameters; -import com.yalantis.ucrop.model.ExifInfo; import com.yalantis.ucrop.model.ImageState; import com.yalantis.ucrop.util.FileUtils; @@ -59,18 +58,14 @@ public class BitmapCropTask implements CropResult{ private final RectFloat mCropRect; private final RectFloat mCurrentImageRect; - private float mCurrentScale, mCurrentAngle; + public float mCurrentScale; + public final float mCurrentAngle; private final int mMaxResultImageSizeX, mMaxResultImageSizeY; - private final String mCompressFormat; - private final int mCompressQuality; public static String mImageInputPath = null; public static String mImageOutputPath = null; - private final ExifInfo mExifInfo; private final BitmapCropCallback mCropCallback; - private int mCroppedImageWidth, mCroppedImageHeight; - private int cropOffsetX, cropOffsetY; private CropResult cropResult; public BitmapCropTask(Context context, PixelMap viewBitmap, ImageState imageState, CropParameters cropParameters, @@ -87,12 +82,8 @@ public class BitmapCropTask implements CropResult{ mMaxResultImageSizeX = cropParameters.getMaxResultImageSizeX(); mMaxResultImageSizeY = cropParameters.getMaxResultImageSizeY(); - mCompressFormat = cropParameters.getCompressFormat(); - mCompressQuality = cropParameters.getCompressQuality(); - mImageInputPath = cropParameters.getImageInputPath(); mImageOutputPath = cropParameters.getImageOutputPath(); - mExifInfo = cropParameters.getExifInfo(); mCropCallback = cropCallback; } @@ -100,34 +91,31 @@ public class BitmapCropTask implements CropResult{ public void doInBackground(){ EventRunner eventRunner = EventRunner.create(); EventHandler handler = new EventHandler(eventRunner); - handler.postTask(new Runnable() { - @Override - public void run() { - if (mViewBitmap == null) { - Throwable t = new NullPointerException("ViewBitmap is null"); - mCropCallback.onCropFailure(t); - return; - } else if (mViewBitmap.isReleased()) { - Throwable t = new NullPointerException("ViewBitmap is null"); - mCropCallback.onCropFailure(t); - return; - } else if (mCurrentImageRect.isEmpty()) { - Throwable t = new NullPointerException("ViewBitmap is null"); - mCropCallback.onCropFailure(t); - return; - } - try { - crop(); - mViewBitmap = null; - } catch (IOException e) { - e.printStackTrace(); - } + handler.postTask(() -> { + if (mViewBitmap == null) { + Throwable t = new NullPointerException("ViewBitmap is null"); + mCropCallback.onCropFailure(t); + return; + } else if (mViewBitmap.isReleased()) { + Throwable t = new NullPointerException("ViewBitmap is null"); + mCropCallback.onCropFailure(t); + return; + } else if (mCurrentImageRect.isEmpty()) { + Throwable t = new NullPointerException("ViewBitmap is null"); + mCropCallback.onCropFailure(t); + return; + } + try { + crop(); + mViewBitmap = null; + } catch (IOException e) { + e.printStackTrace(); } }); } - public String crop() throws IOException { + public void crop() throws IOException { // Downsize if needed if (mMaxResultImageSizeX > 0 && mMaxResultImageSizeY > 0) { float cropWidth = mCropRect.getWidth() / mCurrentScale; @@ -184,10 +172,10 @@ public class BitmapCropTask implements CropResult{ LogUtils.LogInfo("qqqqqqq:","mViewBitmap"+ mViewBitmap); } - cropOffsetX = Math.round((mCropRect.left - mCurrentImageRect.left) / mCurrentScale); - cropOffsetY = Math.round((mCropRect.top - mCurrentImageRect.top) / mCurrentScale); - mCroppedImageWidth = Math.round(mCropRect.getWidth() / mCurrentScale); - mCroppedImageHeight = Math.round(mCropRect.getHeight() / mCurrentScale); + int cropOffsetX = Math.round((mCropRect.left - mCurrentImageRect.left) / mCurrentScale); + int cropOffsetY = Math.round((mCropRect.top - mCurrentImageRect.top) / mCurrentScale); + int mCroppedImageWidth = Math.round(mCropRect.getWidth() / mCurrentScale); + int mCroppedImageHeight = Math.round(mCropRect.getHeight() / mCurrentScale); boolean shouldCrop = shouldCrop(mCroppedImageWidth, mCroppedImageHeight); LogUtils.LogInfo(TAG, "Should crop: " + shouldCrop); @@ -201,17 +189,15 @@ public class BitmapCropTask implements CropResult{ PixelMap pixelMap = PixelMap.create(mViewBitmap, rect, options); //修复错位与错切问题 PixelMap.InitializationOptions options1 = new PixelMap.InitializationOptions(); - options1.size = new Size(mCroppedImageWidth,mCroppedImageHeight); + options1.size = new Size(mCroppedImageWidth, mCroppedImageHeight); PixelMap pixelMap1 = PixelMap.create(pixelMap,options1); - saveImage("CropedFile.jpg", pixelMap1); + saveImage(pixelMap1); Size size = mViewBitmap.getImageInfo().size; LogUtils.LogInfo("qqqqqq:", "rectmViewBitmap" + size.width+"/"+size.height); - LogUtils.LogInfo("qqqqqq:", "rect" + cropOffsetX+"/"+cropOffsetY+"/"+mCroppedImageWidth+"/"+mCroppedImageHeight); - return mImageOutputPath; + LogUtils.LogInfo("qqqqqq:", "rect" + cropOffsetX +"/"+ cropOffsetY +"/"+ mCroppedImageWidth +"/"+ mCroppedImageHeight); } else { FileUtils.copyFile(mImageInputPath, mImageOutputPath); - return mImageOutputPath; } } @@ -219,7 +205,7 @@ public class BitmapCropTask implements CropResult{ /** * 定义回调方法 * - * @param result + * @param result result */ public void onCropResult(CropResult result) { this.cropResult = result; @@ -245,10 +231,10 @@ public class BitmapCropTask implements CropResult{ } - private void saveImage(String fileName, PixelMap pixelMap) { + private void saveImage(PixelMap pixelMap) { try { ValuesBucket valuesBucket = new ValuesBucket(); - valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName); + valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, "CropedFile.jpg"); valuesBucket.putString("relative_path", "DCIM/"); valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG"); //应用独占 @@ -269,6 +255,7 @@ public class BitmapCropTask implements CropResult{ result = imagePacker.addImage(pixelMap); if (result) { long dataSize = imagePacker.finalizePacking(); + System.out.println(dataSize); } } outputStream.flush(); @@ -299,13 +286,15 @@ public class BitmapCropTask implements CropResult{ packingOptions.format = "image/jpeg"; // packingOptions.quality = 90; //预编码 - boolean result = imagePacker.initializePacking(outputStream, packingOptions); + imagePacker.initializePacking(outputStream, packingOptions); //将需要编码的位图放入ImagePacker中,并完成编码 - result = imagePacker.addImage(pixelMap); - long dataSize = imagePacker.finalizePacking(); + imagePacker.addImage(pixelMap); + imagePacker.finalizePacking(); } public PixelMap _loadImage(Context context, File file, Size size, float degrees) { + System.out.println(context); + System.out.println(size); if (file == null) { return null; } @@ -321,9 +310,7 @@ public class BitmapCropTask implements CropResult{ //使用ImageSource的create()函数,将图片读取到ImageSource实例中 ImageSource source = ImageSource.create(file, options); //使用ImageSource的createPixelMap()函数,将ImageSource实例解码为位图实例 - PixelMap pixelMap = source.createPixelmap(decodingOptions); - - return pixelMap; + return source.createPixelmap(decodingOptions); } @Override diff --git a/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapLoadTask.java b/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapLoadTask.java index a1959ded9986ac4f5d99350b857721d78ae19cee..1107c65b8ec6a42bf59f94393d6d6e06f7c92ed1 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapLoadTask.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/task/BitmapLoadTask.java @@ -7,9 +7,6 @@ import ohos.app.Context; //import android.graphics.Bitmap; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; -import ohos.eventhandler.InnerEvent; -import ohos.global.resource.BaseFileDescriptor; -import ohos.media.image.Image; import ohos.media.image.PixelMap; //import android.graphics.BitmapFactory; import ohos.media.image.ImageSource; @@ -36,9 +33,6 @@ import okio.Okio; import okio.Sink; import java.io.*; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; /** @@ -54,7 +48,7 @@ public class BitmapLoadTask { private final Context mContext; private Uri mInputUri; - private Uri mOutputUri; + private final Uri mOutputUri; private final int mRequiredWidth; private final int mRequiredHeight; @@ -82,40 +76,38 @@ public class BitmapLoadTask { public void doInBackground(){ EventRunner eventRunner = EventRunner.create(); EventHandler handler = new EventHandler(eventRunner); - handler.postTask(new Runnable() { - @Override - public void run() { - if (mInputUri == null) { - mBitmapWorkerException = new NullPointerException("Input Uri cannot be null"); - mBitmapLoadCallback.onFailure(mBitmapWorkerException); - return; - } + handler.postTask(() -> { + if (mInputUri == null) { + mBitmapWorkerException = new NullPointerException("Input Uri cannot be null"); + mBitmapLoadCallback.onFailure(mBitmapWorkerException); + return; + } - try { - processInputUri(); - } catch (NullPointerException | IOException e) { - mBitmapWorkerException = e; - mBitmapLoadCallback.onFailure(mBitmapWorkerException); - return; - } - //放在这里有用吗,移动到解码之后? - final ImageSource.DecodingOptions options = new ImageSource.DecodingOptions(); + try { + processInputUri(); + } catch (NullPointerException | IOException e) { + mBitmapWorkerException = e; + mBitmapLoadCallback.onFailure(mBitmapWorkerException); + return; + } + //放在这里有用吗,移动到解码之后? + final ImageSource.DecodingOptions options = new ImageSource.DecodingOptions(); // options.sampleSize = BitmapLoadUtils.calculateInSampleSize(options, mRequiredWidth, mRequiredHeight); - PixelMap decodeSampledBitmap = null; + PixelMap decodeSampledBitmap = null; - boolean decodeAttemptSuccess = false; - while (!decodeAttemptSuccess) { - try { - //安卓通过InputUri获取InputStream - //InputStream stream = mContext.getContentResolver().openInputStream(mInputUri); - //鸿蒙通过InputUri获取InputStream - InputStream stream = null; - DataAbilityHelper helper = DataAbilityHelper.creator(mContext); - FileDescriptor fd = helper.openFile(mInputUri, "r"); - stream = new FileInputStream(fd); - LogUtils.LogInfo("qqqqqq:",String.valueOf(mInputUri)); - LogUtils.LogInfo("qqqqqq:",String.valueOf(stream)); + boolean decodeAttemptSuccess = false; + while (!decodeAttemptSuccess) { + try { + //安卓通过InputUri获取InputStream + //InputStream stream = mContext.getContentResolver().openInputStream(mInputUri); + //鸿蒙通过InputUri获取InputStream + InputStream stream; + DataAbilityHelper helper = DataAbilityHelper.creator(mContext); + FileDescriptor fd = helper.openFile(mInputUri, "r"); + stream = new FileInputStream(fd); + LogUtils.LogInfo("qqqqqq:",String.valueOf(mInputUri)); + LogUtils.LogInfo("qqqqqq:",String.valueOf(stream)); // HttpURLConnection connection = null; // URL url = new URL(String.valueOf(mInputUri)); // URLConnection urlConnection = url.openConnection(); @@ -129,78 +121,77 @@ public class BitmapLoadTask { // // 得到服务器返回过来的流对象 // stream = urlConnection.getInputStream(); // } - try { - ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions(); - ImageSource imageSource = ImageSource.create(stream,sourceOptions); - //一次读取获取原图大小 - decodeSampledBitmap = imageSource.createPixelmap(options); - Size rawSize = decodeSampledBitmap.getImageInfo().size; - LogUtils.LogInfo("qqqqqq:","高"+rawSize.height +"宽"+ rawSize.width); - options.sampleSize = BitmapLoadUtils.calculateInSampleSize(rawSize, mRequiredWidth, mRequiredHeight); - options.desiredSize = new Size(rawSize.width / options.sampleSize, rawSize.height / options.sampleSize); - LogUtils.LogInfo("qqqqqq:","sample size"+ options.sampleSize); - //二次读取,获取缩放后的图像 - decodeSampledBitmap = imageSource.createPixelmap(options); - if (decodeSampledBitmap==null) { - mBitmapWorkerException = new IllegalArgumentException("bitmap could not be retrieved from the Uri: [" + mInputUri + "]"); - mBitmapLoadCallback.onFailure(mBitmapWorkerException); - return; - - } - } finally { - BitmapLoadUtils.close(stream); + try { + ImageSource.SourceOptions sourceOptions = new ImageSource.SourceOptions(); + ImageSource imageSource = ImageSource.create(stream,sourceOptions); + //一次读取获取原图大小 + decodeSampledBitmap = imageSource.createPixelmap(options); + Size rawSize = decodeSampledBitmap.getImageInfo().size; + LogUtils.LogInfo("qqqqqq:","高"+rawSize.height +"宽"+ rawSize.width); + options.sampleSize = BitmapLoadUtils.calculateInSampleSize(rawSize, mRequiredWidth, mRequiredHeight); + options.desiredSize = new Size(rawSize.width / options.sampleSize, rawSize.height / options.sampleSize); + LogUtils.LogInfo("qqqqqq:","sample size"+ options.sampleSize); + //二次读取,获取缩放后的图像 + decodeSampledBitmap = imageSource.createPixelmap(options); + if (decodeSampledBitmap==null) { + mBitmapWorkerException = new IllegalArgumentException("bitmap could not be retrieved from the Uri: [" + mInputUri + "]"); + mBitmapLoadCallback.onFailure(mBitmapWorkerException); + return; + } - if (checkSize(decodeSampledBitmap, options)) continue; - decodeAttemptSuccess = true; - } catch (OutOfMemoryError error) { - LogUtils.LogError(TAG, "doInBackground: BitmapFactory.decodeFileDescriptor: "+error); - options.sampleSize *= 2; - } catch (IOException e) { - LogUtils.LogError(TAG, "doInBackground: ImageDecoder.createSource: "+e); - mBitmapWorkerException = new IllegalArgumentException("PixelMap could not be decoded from the Uri: [" + mInputUri + "]", e); - mBitmapLoadCallback.onFailure(mBitmapWorkerException); - return; - } catch (DataAbilityRemoteException e) { - e.printStackTrace(); - } catch (RuntimeException e){ + } finally { + BitmapLoadUtils.close(stream); } - } - - if (decodeSampledBitmap == null) { - mBitmapWorkerException = new IllegalArgumentException("PixelMap could not be decoded from the Uri: [" + mInputUri + "]"); + if (checkSize(decodeSampledBitmap, options)) continue; + decodeAttemptSuccess = true; + } catch (OutOfMemoryError error) { + LogUtils.LogError(TAG, "doInBackground: BitmapFactory.decodeFileDescriptor: "+error); + options.sampleSize *= 2; + } catch (IOException e) { + LogUtils.LogError(TAG, "doInBackground: ImageDecoder.createSource: "+e); + mBitmapWorkerException = new IllegalArgumentException("PixelMap could not be decoded from the Uri: [" + mInputUri + "]", e); mBitmapLoadCallback.onFailure(mBitmapWorkerException); return; + } catch (DataAbilityRemoteException e) { + e.printStackTrace(); + } catch (RuntimeException e){ + System.out.println(); } + } - int exifOrientation = BitmapLoadUtils.getExifOrientation(mContext, mInputUri); - int exifDegrees = BitmapLoadUtils.exifToDegrees(exifOrientation); - int exifTranslation = BitmapLoadUtils.exifToTranslation(exifOrientation); - - ExifInfo exifInfo = new ExifInfo(exifOrientation, exifDegrees, exifTranslation); + if (decodeSampledBitmap == null) { + mBitmapWorkerException = new IllegalArgumentException("PixelMap could not be decoded from the Uri: [" + mInputUri + "]"); + mBitmapLoadCallback.onFailure(mBitmapWorkerException); + return; + } - Matrix matrix = new Matrix(); - if (exifDegrees != 0) { - matrix.preRotate(exifDegrees); - } - if (exifTranslation != 1) { - matrix.postScale(exifTranslation, 1); - } - if (!matrix.isIdentity()) { - BitmapLoadUtils bitmapLoadUtils = new BitmapLoadUtils(); - mBitmapResult = bitmapLoadUtils.transformBitmap(decodeSampledBitmap, exifDegrees, exifTranslation, mContext); - mExifInfo = exifInfo; - mBitmapLoadCallback.onBitmapLoaded(mBitmapResult, mExifInfo, mInputUri.getDecodedPath(), (mOutputUri == null) ? null : mOutputUri.getDecodedPath()); - return; - } + int exifOrientation = BitmapLoadUtils.getExifOrientation(mContext, mInputUri); + int exifDegrees = BitmapLoadUtils.exifToDegrees(exifOrientation); + int exifTranslation = BitmapLoadUtils.exifToTranslation(exifOrientation); + ExifInfo exifInfo = new ExifInfo(exifOrientation, exifDegrees, exifTranslation); - mBitmapResult = decodeSampledBitmap; - LogUtils.LogInfo("qqqqqqqq:", String.valueOf(mBitmapResult.getImageInfo().size.height)); + Matrix matrix = new Matrix(); + if (exifDegrees != 0) { + matrix.preRotate(exifDegrees); + } + if (exifTranslation != 1) { + matrix.postScale(exifTranslation, 1); + } + if (!matrix.isIdentity()) { + BitmapLoadUtils bitmapLoadUtils = new BitmapLoadUtils(); + mBitmapResult = bitmapLoadUtils.transformBitmap(decodeSampledBitmap, exifDegrees, exifTranslation, mContext); mExifInfo = exifInfo; mBitmapLoadCallback.onBitmapLoaded(mBitmapResult, mExifInfo, mInputUri.getDecodedPath(), (mOutputUri == null) ? null : mOutputUri.getDecodedPath()); - LogUtils.LogInfo("qqqqqq:","main done"); return; } + + + mBitmapResult = decodeSampledBitmap; + LogUtils.LogInfo("qqqqqqqq:", String.valueOf(mBitmapResult.getImageInfo().size.height)); + mExifInfo = exifInfo; + mBitmapLoadCallback.onBitmapLoaded(mBitmapResult, mExifInfo, mInputUri.getDecodedPath(), (mOutputUri == null) ? null : mOutputUri.getDecodedPath()); + LogUtils.LogInfo("qqqqqq:","main done"); }); } @@ -237,13 +228,14 @@ public class BitmapLoadTask { private void copyFile(Uri inputUri, Uri outputUri) throws NullPointerException, IOException { LogUtils.LogDebug(TAG, "copyFile"); + System.out.println(inputUri); if (outputUri == null) { throw new NullPointerException("Output Uri is null - cannot copy image"); } - InputStream inputStream = null; - OutputStream outputStream = null; + InputStream inputStream; + OutputStream outputStream; try { //安卓通过InputUri获取InputStream //inputStream = mContext.getContentResolver().openInputStream(inputUri); @@ -257,7 +249,7 @@ public class BitmapLoadTask { throw new NullPointerException("InputStream for given input Uri is null"); } - byte buffer[] = new byte[1024]; + byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); @@ -265,9 +257,6 @@ public class BitmapLoadTask { } catch (DataAbilityRemoteException e) { e.printStackTrace(); } finally { - BitmapLoadUtils.close(outputStream); - BitmapLoadUtils.close(inputStream); - // swap uris, because input image was copied to the output destination // (cropped image will override it later) mInputUri = mOutputUri; @@ -284,19 +273,20 @@ public class BitmapLoadTask { OkHttpClient client = new OkHttpClient(); BufferedSource source = null; - Sink sink = null; + Sink sink; Response response = null; try { Request request = new Request.Builder() .url(inputUri.toString()) .build(); response = client.newCall(request).execute(); + assert response.body() != null; source = response.body().source(); //安卓通过OutputUri获取OutputStream //OutputStream outputStream = mContext.getContentResolver().openOutputStream(outputUri); //鸿蒙通过OutputUri获取OutputStream - OutputStream outputStream = null; + OutputStream outputStream; DataAbilityHelper helper = DataAbilityHelper.creator(mContext); FileDescriptor fd = helper.openFile(outputUri,"w"); outputStream = new FileOutputStream(fd); @@ -310,7 +300,6 @@ public class BitmapLoadTask { e.printStackTrace(); } finally { BitmapLoadUtils.close(source); - BitmapLoadUtils.close(sink); if (response != null) { BitmapLoadUtils.close(response.body()); } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/BitmapLoadUtils.java b/ucrop/src/main/java/com/yalantis/ucrop/util/BitmapLoadUtils.java index da977a1304052e929b11755a3d74fa4c8f8a7fd2..9c6dbb0096f631feba238313da80fc07d6bf63dc 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/BitmapLoadUtils.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/BitmapLoadUtils.java @@ -1,8 +1,6 @@ package com.yalantis.ucrop.util; //import android.content.Context; -import com.yalantis.ucrop.task.BitmapCropTask; -import ohos.agp.window.service.DisplayAttributes; import ohos.agp.window.service.DisplayManager; import ohos.app.Context; //import android.graphics.PixelMap; @@ -17,11 +15,7 @@ import ohos.hiviewdfx.HiLogLabel; import ohos.media.image.ImageSource; //import android.graphics.Canvas; -import ohos.agp.render.Canvas; - //import android.graphics.Matrix; -import ohos.agp.utils.Matrix; - //import android.graphics.Point; import ohos.agp.utils.Point; @@ -33,13 +27,11 @@ import ohos.utils.net.Uri; //import android.view.Display; import ohos.agp.window.service.Display; //import android.view.WindowManager; -import ohos.agp.window.service.WindowManager; import com.yalantis.ucrop.callback.BitmapLoadCallback; import com.yalantis.ucrop.task.BitmapLoadTask; import java.io.*; -import java.lang.ref.WeakReference; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; @@ -99,13 +91,14 @@ public class BitmapLoadUtils { packingOptions.format = "image/jpeg"; packingOptions.quality = 90; //预编码 - boolean result = imagePacker.initializePacking(outputStream, packingOptions); + imagePacker.initializePacking(outputStream, packingOptions); //将需要编码的位图放入ImagePacker中,并完成编码 - result = imagePacker.addImage(pixelMap); - long dataSize = imagePacker.finalizePacking(); + imagePacker.addImage(pixelMap); + imagePacker.finalizePacking(); } public PixelMap _loadImage(Context context, File file, Size size, float degrees) { + System.out.println(context); if (file == null) { return null; } @@ -121,9 +114,7 @@ public class BitmapLoadUtils { //使用ImageSource的create()函数,将图片读取到ImageSource实例中 ImageSource source = ImageSource.create(file, options); //使用ImageSource的createPixelMap()函数,将ImageSource实例解码为位图实例 - PixelMap pixelMap = source.createPixelmap(decodingOptions); - - return pixelMap; + return source.createPixelmap(decodingOptions); } //【风险】暂时没法用 @@ -145,6 +136,7 @@ public class BitmapLoadUtils { public static int getExifOrientation(Context context, Uri imageUri) { //public static final int ORIENTATION_UNDEFINED = 0; + System.out.println(context); int orientation = 0; try { //安卓通过InputUri获取InputStream @@ -211,13 +203,12 @@ public class BitmapLoadUtils { } /** - * This method calculates maximum size of both width and height of bitmap. - * It is twice the device screen diagonal for default implementation (extra quality to zoom image). - * Size cannot exceed max texture size. + * calculateMaxBitmapSize * - * @return - max bitmap size in pixels. + * @param context context + * @return calculateMaxBitmapSize + * @noinspection checkstyle:JavadocMethod */ - @SuppressWarnings({"SuspiciousNameCombination", "deprecation"}) public static int calculateMaxBitmapSize(Context context) { // WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); DisplayManager wm = DisplayManager.getInstance(); @@ -237,7 +228,6 @@ public class BitmapLoadUtils { int maxBitmapSize = (int) Math.sqrt(Math.pow(width, 2) + Math.pow(height, 2)); // Check for max texture size via Canvas - Canvas canvas = new Canvas(); //鸿蒙无此参数,故预设一个大数 //final int maxCanvasSize = Math.min(canvas.getMaximumBitmapWidth(), canvas.getMaximumBitmapHeight()); final int maxCanvasSize = 10000000; @@ -257,7 +247,7 @@ public class BitmapLoadUtils { @SuppressWarnings("ConstantConditions") public static void close(Closeable c) { - if (c != null && c instanceof Closeable) { // java.lang.IncompatibleClassChangeError: interface not implemented + if (c instanceof Closeable) { // java.lang.IncompatibleClassChangeError: interface not implemented try { c.close(); } catch (IOException e) { diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/Config.java b/ucrop/src/main/java/com/yalantis/ucrop/util/Config.java index 1c6b22022253b291eaa19313e71c6c26b0b8ab4f..9b50c55c60bdef1bed79343668a9dd5625362fba 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/Config.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/Config.java @@ -3,15 +3,6 @@ package com.yalantis.ucrop.util; import ohos.agp.utils.Color; public class Config { - private Float targetAspectRatioX = new Float(0.0); - private Float targetAspectRatioY = new Float(0.0); - private Boolean mCircleDimmedLayer =false; - private int mDimmedColor = 0x88000000; //透明黑 - - private Boolean mShowCropFrame = true; - - - private Boolean mShowCropGrid = true; int cropFrameStrokeSize = 2; int cropFrameColor = Color.RED.getValue(); @@ -28,10 +19,6 @@ public class Config { return mCropGridRowCount; } - public void setmCropGridColumnCount(int mCropGridColumnCount) { - this.mCropGridColumnCount = mCropGridColumnCount; - } - public void setmCropGridRowCount(int mCropGridRowCount) { this.mCropGridRowCount = mCropGridRowCount; } @@ -53,68 +40,28 @@ public class Config { return cropGridStrokeSize; } - public void setCropFrameColor(int cropFrameColor) { - this.cropFrameColor = cropFrameColor; - } - - public void setCropFrameStrokeSize(int cropFrameStrokeSize) { - this.cropFrameStrokeSize = cropFrameStrokeSize; - } - - public void setCropGridColor(int cropGridColor) { - this.cropGridColor = cropGridColor; - } - - public void setCropGridStrokeSize(int cropGridStrokeSize) { - this.cropGridStrokeSize = cropGridStrokeSize; - } - - public Boolean getmShowCropFrame() { - return mShowCropFrame; + return true; } public Boolean getmShowCropGrid() { - return mShowCropGrid; - } - - public void setmShowCropFrame(Boolean mShowCropFrame) { - this.mShowCropFrame = mShowCropFrame; - } - - public void setmShowCropGrid(Boolean mShowCropGrid) { - this.mShowCropGrid = mShowCropGrid; - } - - public void setmCircleDimmedLayer(Boolean mCircleDimmedLayer) { - this.mCircleDimmedLayer = mCircleDimmedLayer; + return true; } public int getmDimmedColor() { - return mDimmedColor; + //透明黑 + return 0x88000000; } public Boolean getmCircleDimmedLayer() { - return mCircleDimmedLayer; - } - - public void setmDimmedColor(int mDimmedColor) { - this.mDimmedColor = mDimmedColor; - } - - public void setTargetAspectRatioX(Float targetAspectRatioX) { - this.targetAspectRatioX = targetAspectRatioX; - } - - public void setTargetAspectRatioY(Float targetAspectRatioY) { - this.targetAspectRatioY = targetAspectRatioY; + return false; } public Float getTargetAspectRatioX() { - return targetAspectRatioX; + return (Float) (float) 0.0; } public Float getTargetAspectRatioY() { - return targetAspectRatioY; + return (Float) (float) 0.0; } } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/CubicEasing.java b/ucrop/src/main/java/com/yalantis/ucrop/util/CubicEasing.java index 3c81b8ec2e21b7122f385c41ce452eb9e9385199..d2bd296148421d122a018a33da3bd58daf90eb7d 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/CubicEasing.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/CubicEasing.java @@ -6,10 +6,6 @@ public final class CubicEasing { return end * ((time = time / duration - 1.0f) * time * time + 1.0f) + start; } - public static float easeIn(float time, float start, float end, float duration) { - return end * (time /= duration) * time * time + start; - } - public static float easeInOut(float time, float start, float end, float duration) { return (time /= duration / 2.0f) < 1.0f ? end / 2.0f * time * time * time + start : end / 2.0f * ((time -= 2.0f) * time * time + 2.0f) + start; } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/FastBitmapDrawable.java b/ucrop/src/main/java/com/yalantis/ucrop/util/FastBitmapDrawable.java index d1ec950e547ce9abb8a023bc1356d43781e32b9c..57449bb136b2f24ec31b342a785d33b6fe646ac4 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/FastBitmapDrawable.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/FastBitmapDrawable.java @@ -19,32 +19,19 @@ package com.yalantis.ucrop.util; import ohos.agp.components.Component; import ohos.agp.components.ComponentContainer; -import ohos.agp.components.Image; import ohos.agp.render.PixelMapHolder; -import ohos.agp.utils.Point; import ohos.app.Context; import ohos.media.image.PixelMap; -//import android.graphics.Canvas; import ohos.agp.render.Canvas; -//import android.graphics.ColorFilter; -import ohos.agp.render.ColorFilter; -//import android.graphics.Paint; import ohos.agp.render.Paint; //import android.graphics.PixelFormat; //import android.graphics.drawable.Drawable; -import ohos.agp.components.element.Element; - -import ohos.media.image.common.PixelFormat; //尝试使用Image替代功能 public class FastBitmapDrawable extends Component implements Component.DrawTask { -// private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG);参数值为0x02 - private final Paint mPaint = new Paint(); - private PixelMap mBitmap; - private int mAlpha; - private int mWidth, mHeight; + private final int mAlpha; public FastBitmapDrawable(Context context, PixelMap b) { super(context); @@ -70,61 +57,18 @@ public class FastBitmapDrawable extends Component implements Component.DrawTask // } // } -// @Override - public void setColorFilter(ColorFilter cf) { - mPaint.setColorFilter(cf); - } - -// @Override - public int getOpacity() { -// return PixelFormat.TRANSLUCENT; - return -3; - } - - public void setFilterBitmap(boolean filterBitmap) { - mPaint.setFilterBitmap(filterBitmap); - } - public float getAlpha() { return mAlpha; } -// @Override - public void setAlpha(int alpha) { - mAlpha = alpha; - mPaint.setAlpha(alpha); - } - -// @Override - public int getIntrinsicWidth() { - return mWidth; - } - -// @Override - public int getIntrinsicHeight() { - return mHeight; - } - -// @Override - public int getMinimumWidth() { - return mWidth; - } - -// @Override - public int getMinimumHeight() { - return mHeight; - } - public PixelMap getBitmap() { return mBitmap; } public void setBitmap(PixelMap b) { // setPixelMap(b); - addDrawTask(new DrawTask() { - @Override - public void onDraw(Component component, Canvas canvas) { - //可以不要? + addDrawTask((component, canvas) -> { + //可以不要? // if (mBitmap != null && !mBitmap.isReleased()) { // PixelMapHolder holder = new PixelMapHolder(mBitmap); // LogUtils.LogInfo("qqqqqqqq:","onDraw"); @@ -133,15 +77,18 @@ public class FastBitmapDrawable extends Component implements Component.DrawTask // canvas.restore(); // // } - } }); mBitmap = b; + int mWidth; + int mHeight; if (b != null) { mWidth = mBitmap.getImageInfo().size.width; mHeight = mBitmap.getImageInfo().size.height; LogUtils.LogInfo("qqqqqq:","setBitmap:bitmap size:" + mHeight + " x " + mWidth); } else { mWidth = mHeight = 0; + System.out.println(mHeight); + System.out.println(mWidth); } } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/FileUtils.java b/ucrop/src/main/java/com/yalantis/ucrop/util/FileUtils.java index 562379378cdf072a268666c5f6ce8d3079df807f..28b2525db2467f5d8d13c2fb62ae303b87a0cb18 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/FileUtils.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/FileUtils.java @@ -15,36 +15,11 @@ */ package com.yalantis.ucrop.util; - -//import android.annotation.SuppressLint; - -//import android.content.ContentUris; - -//import android.content.Context; -import ohos.app.Context; - -//import android.database.Cursor; -import ohos.data.rdb.RdbStore; - -//import android.net.Uri; -import ohos.utils.net.Uri; - -//import android.os.Build; -//import android.os.Environment; -import ohos.app.Environment; -//import android.provider.DocumentsContract; -//import android.provider.MediaStore; -//import android.text.TextUtils; -//import android.util.Log; - import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; -import java.util.Locale; - -//import androidx.annotation.NonNull; /** * @author Peli @@ -53,195 +28,23 @@ import java.util.Locale; */ public class FileUtils { - /** - * TAG for log messages. - */ - private static final String TAG = "FileUtils"; - private FileUtils() { } /** - * @param uri The Uri to check. - * @return Whether the Uri authority is ExternalStorageProvider. - * @author paulburke - */ - public static boolean isExternalStorageDocument(Uri uri) { - return "com.android.externalstorage.documents".equals(uri.getDecodedAuthority()); - } - - /** - * @param uri The Uri to check. - * @return Whether the Uri authority is DownloadsProvider. - * @author paulburke - */ - public static boolean isDownloadsDocument(Uri uri) { - return "com.android.providers.downloads.documents".equals(uri.getDecodedAuthority()); - } - - /** - * @param uri The Uri to check. - * @return Whether the Uri authority is MediaProvider. - * @author paulburke - */ - public static boolean isMediaDocument(Uri uri) { - return "com.android.providers.media.documents".equals(uri.getDecodedAuthority()); - } - - /** - * @param uri The Uri to check. - * @return Whether the Uri authority is Google Photos. - */ - public static boolean isGooglePhotosUri(Uri uri) { - return "com.google.android.apps.photos.content".equals(uri.getDecodedAuthority()); - } - - /** - * Get the value of the data column for this Uri. This is useful for - * MediaStore Uris, and other file-based ContentProviders. - * - * @param context The context. - * @param uri The Uri to query. - * @param selection (Optional) Filter used in the query. - * @param selectionArgs (Optional) Selection arguments used in the query. - * @return The value of the _data column, which is typically a file path. - * @author paulburke - */ - //【暂不提供】 -// public static String getDataColumn(Context context, Uri uri, String selection, -// String[] selectionArgs) { -// -// RdbStore cursor = null; -// final String column = "_data"; -// final String[] projection = { -// column -// }; -// -// try { -// cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, -// null); -// if (cursor != null && cursor.moveToFirst()) { -// final int column_index = cursor.getColumnIndexOrThrow(column); -// return cursor.getString(column_index); -// } -// } catch (IllegalArgumentException ex) { -// LogUtils.i(TAG, String.format(Locale.getDefault(), "getDataColumn: _data - [%s]", ex.getMessage())); -// } finally { -// if (cursor != null) { -// cursor.close(); -// } -// } -// return null; -// } - - /** - * Get a file path from a Uri. This will get the the path for Storage Access - * Framework Documents, as well as the _data field for the MediaStore and - * other file-based ContentProviders.
- *
- * Callers should check whether the path is local before assuming it - * represents a local file. + * copyFile * - * @param context The context. - * @param uri The Uri to query. - * @author paulburke - */ - //@SuppressLint("NewApi") - //【暂不提供】 -// public static String getPath(final Context context, final Uri uri) { -// final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT; -// -// // DocumentProvider -// if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) { -// if (isExternalStorageDocument(uri)) { -// final String docId = DocumentsContract.getDocumentId(uri); -// final String[] split = docId.split(":"); -// final String type = split[0]; -// -// if ("primary".equalsIgnoreCase(type)) { -// return Environment.getExternalStorageDirectory() + "/" + split[1]; -// } -// -// // TODO handle non-primary volumes -// } -// // DownloadsProvider -// else if (isDownloadsDocument(uri)) { -// -// final String id = DocumentsContract.getDocumentId(uri); -// if (!TextUtils.isEmpty(id)) { -// try { -// final Uri contentUri = ContentUris.withAppendedId( -// Uri.parse("content://downloads/public_downloads"), Long.valueOf(id)); -// return getDataColumn(context, contentUri, null, null); -// } catch (NumberFormatException e) { -// LogUtils.i(TAG, e.getMessage()); -// return null; -// } -// } -// -// } -// // MediaProvider -// else if (isMediaDocument(uri)) { -// final String docId = DocumentsContract.getDocumentId(uri); -// final String[] split = docId.split(":"); -// final String type = split[0]; -// -// Uri contentUri = null; -// if ("image".equals(type)) { -// contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI; -// } else if ("video".equals(type)) { -// contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI; -// } else if ("audio".equals(type)) { -// contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; -// } -// -// final String selection = "_id=?"; -// final String[] selectionArgs = new String[]{ -// split[1] -// }; -// -// return getDataColumn(context, contentUri, selection, selectionArgs); -// } -// } -// // MediaStore (and general) -// else if ("content".equalsIgnoreCase(uri.getScheme())) { -// -// // Return the remote address -// if (isGooglePhotosUri(uri)) { -// return uri.getLastPathSegment(); -// } -// -// return getDataColumn(context, uri, null, null); -// } -// // File -// else if ("file".equalsIgnoreCase(uri.getScheme())) { -// return uri.getPath(); -// } -// -// return null; -// } - - /** - * Copies one file into the other with the given paths. - * In the event that the paths are the same, trying to copy one file to the other - * will cause both files to become null. - * Simply skipping this step if the paths are identical. + * @param pathFrom pathFrom + * @param pathTo pathTo + * @throws IOException IOException */ public static void copyFile( String pathFrom, String pathTo) throws IOException { if (pathFrom.equalsIgnoreCase(pathTo)) { return; } - FileChannel outputChannel = null; - FileChannel inputChannel = null; - try { - inputChannel = new FileInputStream(new File(pathFrom)).getChannel(); - outputChannel = new FileOutputStream(new File(pathTo)).getChannel(); + try (FileChannel inputChannel = new FileInputStream(new File(pathFrom)).getChannel(); FileChannel outputChannel = new FileOutputStream(new File(pathTo)).getChannel()) { inputChannel.transferTo(0, inputChannel.size(), outputChannel); - inputChannel.close(); - } finally { - if (inputChannel != null) inputChannel.close(); - if (outputChannel != null) outputChannel.close(); } } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/ImageHeaderParser.java b/ucrop/src/main/java/com/yalantis/ucrop/util/ImageHeaderParser.java index 4583fbe03ae932e6f4c0b7458722ad32f127c6fe..e40f2d718243fc0f3554ec03e74221773b15871e 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/ImageHeaderParser.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/ImageHeaderParser.java @@ -37,16 +37,12 @@ import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; -import java.nio.charset.Charset; - -//import androidx.exifinterface.media.ExifInterface; -import ohos.media.image.common.PropertyKey.Exif; +import java.nio.charset.StandardCharsets; /** * A class for parsing the exif orientation from an image header. */ public class ImageHeaderParser { - private static final String TAG = "ImageHeaderParser"; /** * A constant indicating we were unable to parse the orientation from the image either because * no exif segment containing orientation data existed, or because of an I/O error attempting to @@ -61,7 +57,7 @@ public class ImageHeaderParser { private static final int INTEL_TIFF_MAGIC_NUMBER = 0x4949; private static final String JPEG_EXIF_SEGMENT_PREAMBLE = "Exif\0\0"; private static final byte[] JPEG_EXIF_SEGMENT_PREAMBLE_BYTES = - JPEG_EXIF_SEGMENT_PREAMBLE.getBytes(Charset.forName("UTF-8")); + JPEG_EXIF_SEGMENT_PREAMBLE.getBytes(StandardCharsets.UTF_8); private static final int SEGMENT_SOS = 0xDA; private static final int MARKER_EOI = 0xD9; private static final int SEGMENT_START_ID = 0xFF; @@ -81,22 +77,16 @@ public class ImageHeaderParser { * * @return The exif orientation if present or -1 if the header couldn't be parsed or doesn't * contain an orientation - * @throws IOException + * @throws IOException IOException */ public int getOrientation() throws IOException { final int magicNumber = reader.getUInt16(); if (!handles(magicNumber)) { - if (true) { - LogUtils.LogDebug(TAG, "Parser doesn't handle magic number: " + magicNumber); - } return UNKNOWN_ORIENTATION; } else { int exifSegmentLength = moveToExifSegmentAndGetLength(); if (exifSegmentLength == -1) { - if (true) { - LogUtils.LogDebug(TAG, "Failed to parse exif segment length, or exif segment not found"); - } return UNKNOWN_ORIENTATION; } @@ -108,11 +98,6 @@ public class ImageHeaderParser { private int parseExifSegment(byte[] tempArray, int exifSegmentLength) throws IOException { int read = reader.read(tempArray, exifSegmentLength); if (read != exifSegmentLength) { - if (true) { - LogUtils.LogDebug(TAG, "Unable to read exif segment data" - + ", length: " + exifSegmentLength - + ", actually read: " + read); - } return UNKNOWN_ORIENTATION; } @@ -120,9 +105,6 @@ public class ImageHeaderParser { if (hasJpegExifPreamble) { return parseExifSegment(new RandomAccessReader(tempArray, exifSegmentLength)); } else { - if (true) { - LogUtils.LogDebug(TAG, "Missing jpeg exif preamble"); - } return UNKNOWN_ORIENTATION; } } @@ -142,8 +124,11 @@ public class ImageHeaderParser { } /** - * Moves reader to the start of the exif segment and returns the length of the exif segment or - * {@code -1} if no exif segment is found. + * moveToExifSegmentAndGetLength + * + * @return moveToExifSegmentAndGetLength + * @throws IOException IOException + * @noinspection checkstyle:JavadocMethod */ private int moveToExifSegmentAndGetLength() throws IOException { short segmentId, segmentType; @@ -151,9 +136,6 @@ public class ImageHeaderParser { while (true) { segmentId = reader.getUInt8(); if (segmentId != SEGMENT_START_ID) { - if (true) { - LogUtils.LogDebug(TAG, "Unknown segmentId=" + segmentId); - } return -1; } @@ -162,9 +144,6 @@ public class ImageHeaderParser { if (segmentType == SEGMENT_SOS) { return -1; } else if (segmentType == MARKER_EOI) { - if (true) { - LogUtils.LogDebug(TAG, "Found MARKER_EOI in exif segment"); - } return -1; } @@ -174,12 +153,6 @@ public class ImageHeaderParser { if (segmentType != EXIF_SEGMENT_TYPE) { long skipped = reader.skip(segmentLength); if (skipped != segmentLength) { - if (true) { - LogUtils.LogDebug(TAG, "Unable to skip enough data" - + ", type: " + segmentType - + ", wanted to skip: " + segmentLength - + ", but actually skipped: " + skipped); - } return -1; } } else { @@ -198,9 +171,6 @@ public class ImageHeaderParser { } else if (byteOrderIdentifier == INTEL_TIFF_MAGIC_NUMBER) { byteOrder = ByteOrder.LITTLE_ENDIAN; } else { - if (true) { - LogUtils.LogDebug(TAG, "Unknown endianness = " + byteOrderIdentifier); - } byteOrder = ByteOrder.BIG_ENDIAN; } @@ -223,48 +193,28 @@ public class ImageHeaderParser { // 12 is max format code. if (formatCode < 1 || formatCode > 12) { - if (true) { - LogUtils.LogDebug(TAG, "Got invalid format code = " + formatCode); - } continue; } componentCount = segmentData.getInt32(tagOffset + 4); if (componentCount < 0) { - if (true) { - LogUtils.LogDebug(TAG, "Negative tiff component count"); - } continue; } - if (true) { - LogUtils.LogDebug(TAG, "Got tagIndex=" + i + " tagType=" + tagType + " formatCode=" + formatCode - + " componentCount=" + componentCount); - } - final int byteCount = componentCount + BYTES_PER_FORMAT[formatCode]; if (byteCount > 4) { - if (true) { - LogUtils.LogDebug(TAG, "Got byte count > 4, not orientation, continuing, formatCode=" + formatCode); - } continue; } final int tagValueOffset = tagOffset + 8; if (tagValueOffset < 0 || tagValueOffset > segmentData.length()) { - if (true) { - LogUtils.LogDebug(TAG, "Illegal tagValueOffset=" + tagValueOffset + " tagType=" + tagType); - } continue; } if (byteCount < 0 || tagValueOffset + byteCount > segmentData.length()) { - if (true) { - LogUtils.LogDebug(TAG, "Illegal number of bytes for TI tag data tagType=" + tagType); - } continue; } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/LogUtils.java b/ucrop/src/main/java/com/yalantis/ucrop/util/LogUtils.java index b4b3e4e55378edf7c0e0b49421bfca4f10325809..402d5b2aff6fad65ce782de7d8c63c02065024ed 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/LogUtils.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/LogUtils.java @@ -1,6 +1,5 @@ package com.yalantis.ucrop.util; -import ohos.hiviewdfx.Debug; import ohos.hiviewdfx.HiLog; import ohos.hiviewdfx.HiLogLabel; @@ -17,8 +16,4 @@ public class LogUtils { HiLogLabel hiLogLabel = new HiLogLabel(3,0,tag); HiLog.error(hiLogLabel,words,"asd"); } - public static void isLoggable(String tag, String words){ - HiLogLabel hiLogLabel = new HiLogLabel(3,0,tag); - HiLog.error(hiLogLabel,words,"asd"); - } } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/RectUtils.java b/ucrop/src/main/java/com/yalantis/ucrop/util/RectUtils.java index 2813f7b3f9347f517600280cfaa36503dc652107..435bafa1a8124d2b3d17305d0c9c1cdf22bce9a3 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/RectUtils.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/RectUtils.java @@ -61,17 +61,17 @@ public class RectUtils { for (int i = 1; i < array.length; i += 2) { float x = Math.round(array[i - 1] * 10) / 10.f; float y = Math.round(array[i] * 10) / 10.f; - r.left = (x < r.left) ? x : r.left; - r.top = (y < r.top) ? y : r.top; - r.right = (x > r.right) ? x : r.right; - r.bottom = (y > r.bottom) ? y : r.bottom; + r.left = Math.min(x, r.left); + r.top = Math.min(y, r.top); + r.right = Math.max(x, r.right); + r.bottom = Math.max(y, r.bottom); } - r = reorder(r); + reorder(r); return r; } - private static RectFloat reorder(RectFloat r){ + private static void reorder(RectFloat r){ if(r.right <= r.left){ float temp = r.right; r.right = r.left; @@ -82,7 +82,6 @@ public class RectUtils { r.bottom = r.top; r.top = temp; } - return r; } } \ No newline at end of file diff --git a/ucrop/src/main/java/com/yalantis/ucrop/util/RotationGestureDetector.java b/ucrop/src/main/java/com/yalantis/ucrop/util/RotationGestureDetector.java index 4ab47b502b0d77bb0af8d4d7e86444b0c06f1f52..149b2e9a9d05b5f9fbcc8b9dad855ad8f90f1821 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/util/RotationGestureDetector.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/util/RotationGestureDetector.java @@ -14,7 +14,7 @@ public class RotationGestureDetector { private float mAngle; private boolean mIsFirstTouch; - private OnRotationGestureListener mListener; + private final OnRotationGestureListener mListener; public RotationGestureDetector(OnRotationGestureListener listener) { mListener = listener; @@ -26,7 +26,7 @@ public class RotationGestureDetector { return mAngle; } - public boolean onTouchEvent(TouchEvent event) { + public void onTouchEvent(TouchEvent event) { switch (event.getAction()) { case TouchEvent.PRIMARY_POINT_DOWN: sX = event.getPointerPosition(0).getX(); @@ -74,17 +74,16 @@ public class RotationGestureDetector { mPointerIndex2 = INVALID_POINTER_INDEX; break; } - return true; } - private float calculateAngleBetweenLines(float fx1, float fy1, float fx2, float fy2, - float sx1, float sy1, float sx2, float sy2) { - return calculateAngleDelta( + private void calculateAngleBetweenLines(float fx1, float fy1, float fx2, float fy2, + float sx1, float sy1, float sx2, float sy2) { + calculateAngleDelta( (float) Math.toDegrees((float) Math.atan2((fy1 - fy2), (fx1 - fx2))), (float) Math.toDegrees((float) Math.atan2((sy1 - sy2), (sx1 - sx2)))); } - private float calculateAngleDelta(float angleFrom, float angleTo) { + private void calculateAngleDelta(float angleFrom, float angleTo) { mAngle = angleTo % 360.0f - angleFrom % 360.0f; if (mAngle < -180.0f) { @@ -93,20 +92,17 @@ public class RotationGestureDetector { mAngle -= 360.0f; } - return mAngle; } public static class SimpleOnRotationGestureListener implements OnRotationGestureListener { @Override - public boolean onRotation(RotationGestureDetector rotationDetector) { - return false; + public void onRotation(RotationGestureDetector rotationDetector) { } } public interface OnRotationGestureListener { - - boolean onRotation(RotationGestureDetector rotationDetector); + void onRotation(RotationGestureDetector rotationDetector); } } \ No newline at end of file diff --git a/ucrop/src/main/java/com/yalantis/ucrop/view/CropImageView.java b/ucrop/src/main/java/com/yalantis/ucrop/view/CropImageView.java index e1dc981474a5ff55910928a5261a06ddd5b3321b..67eb31b2d47b444d6956ed1db7916880645843b6 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/view/CropImageView.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/view/CropImageView.java @@ -17,14 +17,11 @@ import java.util.Arrays; import ohos.agp.components.AttrSet; import ohos.agp.components.Component; -import ohos.agp.components.Image; -import ohos.agp.components.element.Element; import ohos.agp.utils.Matrix; import ohos.agp.utils.RectFloat; import ohos.app.Context; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; -import ohos.global.resource.solidxml.TypedAttribute; /** * Created by Oleksii Shliama (https://github.com/shliama). @@ -34,49 +31,41 @@ import ohos.global.resource.solidxml.TypedAttribute; */ public class CropImageView extends TransformImageView { - public static final int DEFAULT_MAX_BITMAP_SIZE = 0; public static final int DEFAULT_IMAGE_TO_CROP_BOUNDS_ANIM_DURATION = 500; public static final float DEFAULT_MAX_SCALE_MULTIPLIER = 10.0f; public static final float SOURCE_IMAGE_ASPECT_RATIO = 0f; - public static final float DEFAULT_ASPECT_RATIO = SOURCE_IMAGE_ASPECT_RATIO; private final RectFloat mCropRect = new RectFloat(); private final Matrix mTempMatrix = new Matrix(); private float mTargetAspectRatio; - private float mMaxScaleMultiplier = DEFAULT_MAX_SCALE_MULTIPLIER; private CropBoundsChangeListener mCropBoundsChangeListener; - private Runnable mWrapCropBoundsRunnable, mZoomImageToPositionRunnable = null; + private Runnable mWrapCropBoundsRunnable; - private float mMaxScale, mMinScale; - private int mMaxResultImageSizeX = 0, mMaxResultImageSizeY = 0; - private long mImageToWrapCropBoundsAnimDuration = DEFAULT_IMAGE_TO_CROP_BOUNDS_ANIM_DURATION; - private EventRunner eventRunner ; - private EventHandler eventHandler ; + private float mMaxScale; + private final EventHandler eventHandler ; - public CropImageView(Context context) { - this(context, null); - } - - public CropImageView(Context context, AttrSet attrs) { - this(context, attrs, "0"); - } - - public CropImageView(Context context, AttrSet attrs, String defStyle) { - super(context, attrs, defStyle); - eventRunner = EventRunner.getMainEventRunner(); + public CropImageView(Context context, AttrSet attrs, String s) { + super(context, attrs, "0"); + System.out.println(s); + EventRunner eventRunner = EventRunner.getMainEventRunner(); eventHandler = new EventHandler(eventRunner); } /** - * Cancels all current animations and sets image to fill crop area (without animation). - * Then creates and executes {@link BitmapCropTask} with proper parameters. + * cropAndSaveImage + * + * @param compressFormat compressFormat + * @param compressQuality compressQuality + * @param cropCallback cropCallback + * @param context context */ public void cropAndSaveImage(String compressFormat, int compressQuality, BitmapCropCallback cropCallback,Context context) { + System.out.println(context); cancelAllAnimations(); setImageToWrapCropBounds(false); @@ -84,6 +73,8 @@ public class CropImageView extends TransformImageView { mCropRect, RectUtils.trapToRect(mCurrentImageCorners), getCurrentScale(), getCurrentAngle()); + int mMaxResultImageSizeX = 0; + int mMaxResultImageSizeY = 0; final CropParameters cropParameters = new CropParameters( mMaxResultImageSizeX, mMaxResultImageSizeY, compressFormat, compressQuality, @@ -94,11 +85,6 @@ public class CropImageView extends TransformImageView { urlpath.doInBackground(); } private CropResult cropResult; - /** - * 定义回调方法 - * - * @param result - */ public void onCropResult(CropResult result) { this.cropResult = result; } @@ -110,20 +96,6 @@ public class CropImageView extends TransformImageView { return mMaxScale; } - /** - * @return - minimum scale value for current image and crop ratio - */ - public float getMinScale() { - return mMinScale; - } - - /** - * @return - aspect ratio for crop bounds - */ - public float getTargetAspectRatio() { - return mTargetAspectRatio; - } - /** * Updates current crop rectangle with given. Also recalculates image properties and position * to fit new crop rectangle. @@ -138,105 +110,16 @@ public class CropImageView extends TransformImageView { setImageToWrapCropBounds(); } - /** - * This method sets aspect ratio for crop bounds. - * If {@link #SOURCE_IMAGE_ASPECT_RATIO} value is passed - aspect ratio is calculated - * based on current image width and height. - * - * @param targetAspectRatio - aspect ratio for image crop (e.g. 1.77(7) for 16:9) - */ - public void setTargetAspectRatio(float targetAspectRatio) { - final Image drawable = (Image)getComponentAt(0); - if (drawable == null) { - mTargetAspectRatio = targetAspectRatio; - return; - } - - if (targetAspectRatio == SOURCE_IMAGE_ASPECT_RATIO) { - mTargetAspectRatio = 404 / (float) 606; - } else { - mTargetAspectRatio = targetAspectRatio; - } - - if (mCropBoundsChangeListener != null) { - mCropBoundsChangeListener.onCropAspectRatioChanged(mTargetAspectRatio); - } - } - - - public CropBoundsChangeListener getCropBoundsChangeListener() { - return mCropBoundsChangeListener; - } - public void setCropBoundsChangeListener( CropBoundsChangeListener cropBoundsChangeListener) { mCropBoundsChangeListener = cropBoundsChangeListener; } /** - * This method sets maximum width for resulting cropped image - * - * @param maxResultImageSizeX - size in pixels - */ - public void setMaxResultImageSizeX( int maxResultImageSizeX) { - mMaxResultImageSizeX = maxResultImageSizeX; - } - - /** - * This method sets maximum width for resulting cropped image + * zoomInImage * - * @param maxResultImageSizeY - size in pixels - */ - public void setMaxResultImageSizeY( int maxResultImageSizeY) { - mMaxResultImageSizeY = maxResultImageSizeY; - } - - /** - * This method sets animation duration for image to wrap the crop bounds - * - * @param imageToWrapCropBoundsAnimDuration - duration in milliseconds - */ - public void setImageToWrapCropBoundsAnimDuration( long imageToWrapCropBoundsAnimDuration) { - if (imageToWrapCropBoundsAnimDuration > 0) { - mImageToWrapCropBoundsAnimDuration = imageToWrapCropBoundsAnimDuration; - } else { - throw new IllegalArgumentException("Animation duration cannot be negative value."); - } - } - - /** - * This method sets multiplier that is used to calculate max image scale from min image scale. - * - * @param maxScaleMultiplier - (minScale * maxScaleMultiplier) = maxScale - */ - public void setMaxScaleMultiplier(float maxScaleMultiplier) { - mMaxScaleMultiplier = maxScaleMultiplier; - } - - /** - * This method scales image down for given value related to image center. - */ - public void zoomOutImage(float deltaScale) { - zoomOutImage(deltaScale, (float) (mCropRect.left+0.5*mCropRect.getWidth()), (float) (mCropRect.right+0.5*mCropRect.getHeight())); - } - - /** - * This method scales image down for given value related given coords (x, y). - */ - public void zoomOutImage(float scale, float centerX, float centerY) { - if (scale >= getMinScale()) { - postScale(scale / getCurrentScale(), centerX, centerY); - } - } - - /** - * This method scales image up for given value related to image center. - */ - public void zoomInImage(float deltaScale) { - zoomInImage(deltaScale,(float) (mCropRect.left+0.5*mCropRect.getWidth()), (float) (mCropRect.right+0.5*mCropRect.getHeight())); - } - - /** - * This method scales image up for given value related to given coords (x, y). + * @param scale scale + * @param centerX centerX + * @param centerY centerY */ public void zoomInImage(float scale, float centerX, float centerY) { if (scale <= getMaxScale()) { @@ -260,22 +143,13 @@ public class CropImageView extends TransformImageView { } } - /** - * This method rotates image for given angle related to the image center. - * - * @param deltaAngle - angle to rotate - */ - public void postRotate(float deltaAngle) { - postRotate(deltaAngle, (float) (mCropRect.left+0.5*mCropRect.getWidth()), (float) (mCropRect.right+0.5*mCropRect.getHeight())); - } - /** * This method cancels all current Runnable objects that represent animations. */ public void cancelAllAnimations() { eventHandler.removeTask(mWrapCropBoundsRunnable); - eventHandler.removeTask(mZoomImageToPositionRunnable); + eventHandler.removeTask(null); } public void setImageToWrapCropBounds() { @@ -283,12 +157,9 @@ public class CropImageView extends TransformImageView { } /** - * If image doesn't fill the crop bounds it must be translated and scaled properly to fill those. - *

- * Therefore this method calculates delta X, Y and scale values and passes them to the - * {@link WrapCropBoundsRunnable} which animates image. - * Scale value must be calculated only if image won't fill the crop bounds after it's translated to the - * crop bounds rectangle center. Using temporary variables this method checks this case. + * setImageToWrapCropBounds + * + * @param animate animate */ public void setImageToWrapCropBounds(boolean animate) { if (mBitmapLaidOut && !isImageWrapCropBounds()) { @@ -297,8 +168,8 @@ public class CropImageView extends TransformImageView { float currentY = mCurrentImageCenter[1]; float currentScale = getCurrentScale(); //裁剪框的中心点坐标减去图像的中心点坐标 - float deltaX = (float) (mCropRect.getCenter().position[0]) - currentX; - float deltaY = (float) (mCropRect.getCenter().position[1]) - currentY; + float deltaX = mCropRect.getCenter().position[0] - currentX; + float deltaY = mCropRect.getCenter().position[1] - currentY; float deltaScale = 0; mTempMatrix.reset(); @@ -328,14 +199,14 @@ public class CropImageView extends TransformImageView { if (animate) { eventHandler.postTask(mWrapCropBoundsRunnable = new WrapCropBoundsRunnable( - CropImageView.this, mImageToWrapCropBoundsAnimDuration, currentX, currentY, deltaX, deltaY, - currentScale, deltaScale, willImageWrapCropBoundsAfterTranslate)); + CropImageView.this, DEFAULT_IMAGE_TO_CROP_BOUNDS_ANIM_DURATION, currentX, currentY, deltaX, deltaY, + currentScale, deltaScale, true)); LogUtils.LogInfo("qqqqqqq:","setImageToWrapCropBounds to setMatrix, DeltaX & DeltaY:"+ deltaX +"/" + deltaY); } else { postTranslate(deltaX, deltaY); - if (!willImageWrapCropBoundsAfterTranslate) { - zoomInImage(currentScale + deltaScale, mCropRect.getCenter().position[0], mCropRect.getCenter().position[1]); - } +// if (!willImageWrapCropBoundsAfterTranslate) { +// zoomInImage(currentScale + deltaScale, mCropRect.getCenter().position[0], mCropRect.getCenter().position[1]); +// } } } } @@ -366,7 +237,7 @@ public class CropImageView extends TransformImageView { float deltaRight = unrotatedImageRect.right - unrotatedCropRect.right; float deltaBottom = unrotatedImageRect.bottom - unrotatedCropRect.bottom; - float indents[] = new float[4]; + float[] indents = new float[4]; indents[0] = (deltaLeft > 0) ? deltaLeft : 0; indents[1] = (deltaTop > 0) ? deltaTop : 0; indents[2] = (deltaRight < 0) ? deltaRight : 0; @@ -421,9 +292,12 @@ public class CropImageView extends TransformImageView { } /** - * This method checks whether current image fills the crop bounds. + * isImageWrapCropBounds + * + * @return isImageWrapCropBounds + * @noinspection checkstyle:JavadocMethod */ - protected boolean isImageWrapCropBounds() { + public boolean isImageWrapCropBounds() { return isImageWrapCropBounds(mCurrentImageCorners); } @@ -448,26 +322,6 @@ public class CropImageView extends TransformImageView { return RectUtils.trapToRect(unrotatedImageCorners).isInclude(RectUtils.trapToRect(unrotatedCropBoundsCorners)); } - /** - * This method changes image scale (animating zoom for given duration), related to given center (x,y). - * - * @param scale - target scale - * @param centerX - scale center X - * @param centerY - scale center Y - * @param durationMs - zoom animation duration - */ - protected void zoomImageToPosition(float scale, float centerX, float centerY, long durationMs) { - if (scale > getMaxScale()) { - scale = getMaxScale(); - } - - final float oldScale = getCurrentScale(); - final float deltaScale = scale - oldScale; - - eventHandler.postTask(mZoomImageToPositionRunnable = new ZoomImageToPosition(CropImageView.this, - durationMs, oldScale, deltaScale, centerX, centerY)); - } - private void calculateImageScaleBounds() { final Component drawable = getComponentAt(0); if (drawable == null) { @@ -486,8 +340,8 @@ public class CropImageView extends TransformImageView { float widthScale = Math.min(mCropRect.getWidth() / drawableWidth, mCropRect.getWidth() / drawableHeight); float heightScale = Math.min(mCropRect.getHeight() / drawableHeight, mCropRect.getHeight() / drawableWidth); - mMinScale = Math.min(widthScale, heightScale); - mMaxScale = mMinScale * mMaxScaleMultiplier; + float mMinScale = Math.min(widthScale, heightScale); + mMaxScale = mMinScale * DEFAULT_MAX_SCALE_MULTIPLIER; } /** @@ -517,10 +371,10 @@ public class CropImageView extends TransformImageView { } /** - * This method extracts all needed values from the styled attributes. - * Those are used to configure the view. + * processStyledAttributes + * + * @param a a */ - @SuppressWarnings("deprecation") protected void processStyledAttributes( Config a) { // float targetAspectRatioX = Math.abs(a.getFloat(R.styleable.ucrop_UCropView_ucrop_aspect_ratio_x, DEFAULT_ASPECT_RATIO)); // float targetAspectRatioY = Math.abs(a.getFloat(R.styleable.ucrop_UCropView_ucrop_aspect_ratio_y, DEFAULT_ASPECT_RATIO)); @@ -596,56 +450,4 @@ public class CropImageView extends TransformImageView { } } - /** - * This Runnable is used to animate an image zoom. - * Given values are interpolated during the animation time. - * Runnable can be terminated either vie {@link #cancelAllAnimations()} method - * or when certain conditions inside {@link ZoomImageToPosition#run()} method are triggered. - */ - private static class ZoomImageToPosition implements Runnable { - - private final WeakReference mCropImageView; - - private final long mDurationMs, mStartTime; - private final float mOldScale; - private final float mDeltaScale; - private final float mDestX; - private final float mDestY; - - public ZoomImageToPosition(CropImageView cropImageView, - long durationMs, - float oldScale, float deltaScale, - float destX, float destY) { - - mCropImageView = new WeakReference<>(cropImageView); - - mStartTime = System.currentTimeMillis(); - mDurationMs = durationMs; - mOldScale = oldScale; - mDeltaScale = deltaScale; - mDestX = destX; - mDestY = destY; - } - - @Override - public void run() { - CropImageView cropImageView = mCropImageView.get(); - if (cropImageView == null) { - return; - } - - long now = System.currentTimeMillis(); - float currentMs = Math.min(mDurationMs, now - mStartTime); - float newScale = CubicEasing.easeInOut(currentMs, 0, mDeltaScale, mDurationMs); - - if (currentMs < mDurationMs) { - cropImageView.zoomInImage(mOldScale + newScale, mDestX, mDestY); - cropImageView.eventHandler.postTask(this); - } else { - cropImageView.setImageToWrapCropBounds(); - } - } - - } - } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/view/CropResult.java b/ucrop/src/main/java/com/yalantis/ucrop/view/CropResult.java index 9752b2fd42a6142b473302daad19cdb97501ab31..11ac88df0939d5a62f2f6d598f355be1a118f4e4 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/view/CropResult.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/view/CropResult.java @@ -3,15 +3,9 @@ package com.yalantis.ucrop.view; /** * 裁剪回调 * - * @author + * @author ImageSelector * @since 2021-04-25 */ public interface CropResult { - - /** - * 回调 - * - * @param path - */ void onCropResult(String path); } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/view/GestureCropImageView.java b/ucrop/src/main/java/com/yalantis/ucrop/view/GestureCropImageView.java index ec237cf07c2ec0dc85b04d4f4020ff90451d81ed..a18bed771e068e1f2ba37f125164670d8db895f5 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/view/GestureCropImageView.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/view/GestureCropImageView.java @@ -13,113 +13,24 @@ import ohos.multimodalinput.event.TouchEvent; * Created by Oleksii Shliama (https://github.com/shliama). */ public class GestureCropImageView extends CropImageView implements Component.TouchEventListener { - - private static final int DOUBLE_TAP_ZOOM_DURATION = 200; - -// private ScaleGestureDetector mScaleDetector; //暂不提供手势 private RotationGestureDetector mRotateDetector; -// private GestureDetector mGestureDetector; - ScaleListener mScaledListener; - ScrolledListener mScrolledListener; private float before_X = -1; private float before_Y = -1; private float mMidPntX, mMidPntY; - - private boolean mIsRotateEnabled = true; - private boolean mIsScaleEnabled = true; - private int mDoubleTapScaleSteps = 5; - - public GestureCropImageView(Context context) { - super(context); - } - public GestureCropImageView(Context context, AttrSet attrs) { - this(context, attrs, "0"); - } - - public GestureCropImageView(Context context, AttrSet attrs, String defStyle) { - super(context, attrs, defStyle); - } - - public void setScaleEnabled(boolean scaleEnabled) { - mIsScaleEnabled = scaleEnabled; - } - - public boolean isScaleEnabled() { - return mIsScaleEnabled; - } - - public void setRotateEnabled(boolean rotateEnabled) { - mIsRotateEnabled = rotateEnabled; + super(context, attrs, "0"); } - public boolean isRotateEnabled() { - return mIsRotateEnabled; - } - - public void setDoubleTapScaleSteps(int doubleTapScaleSteps) { - mDoubleTapScaleSteps = doubleTapScaleSteps; - } - - public int getDoubleTapScaleSteps() { - return mDoubleTapScaleSteps; - } - - /** - * If it's ACTION_DOWN event - user touches the screen and all current animation must be canceled. - * If it's ACTION_UP event - user removed all fingers from the screen and current image position must be corrected. - * If there are more than 2 fingers - update focal point coordinates. - * Pass the event to the gesture detectors if those are enabled. - */ -// @Override -// public boolean onTouchEvent(MotionEvent event) { -// if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN) { -// cancelAllAnimations(); -// } -// -// if (event.getPointerCount() > 1) { -// mMidPntX = (event.getX(0) + event.getX(1)) / 2; -// mMidPntY = (event.getY(0) + event.getY(1)) / 2; -// } -// -// mGestureDetector.onTouchEvent(event); -// -// if (mIsScaleEnabled) { -// mScaleDetector.onTouchEvent(event); -// } -// -// if (mIsRotateEnabled) { -// mRotateDetector.onTouchEvent(event); -// } -// -// if ((event.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_UP) { -// setImageToWrapCropBounds(); -// } -// return true; -// } - @Override protected void init() { super.init(); setupGestureListeners(); } - /** - * This method calculates target scale value for double tap gesture. - * User is able to zoom the image from min scale value - * to the max scale value with {@link #mDoubleTapScaleSteps} double taps. - */ - protected float getDoubleTapTargetScale() { - return getCurrentScale() * (float) Math.pow(getMaxScale() / getMinScale(), 1.0f / mDoubleTapScaleSteps); - } - private void setupGestureListeners() { -// mGestureDetector = new GestureDetector(getContext(), new GestureListener(), null, true); -// mScaleDetector = new Component.ScaledListener(getContext(), new ScaleListener); - //旋转监听 mRotateDetector = new RotationGestureDetector(new RotateListener()); @@ -128,8 +39,6 @@ public class GestureCropImageView extends CropImageView implements Component.Tou //缩放监听 mScaledListener = new ScaleListener(); setScaledListener(mScaledListener); - - } //由于鸿蒙滑动监听缺陷,所以滑动操作整合在触摸监听里 @Override @@ -163,14 +72,9 @@ public class GestureCropImageView extends CropImageView implements Component.Tou // mGestureDetector.onTouchEvent(event); - if (mIsScaleEnabled) { -// mScaleDetector.onTouchEvent(event); - } - - if (mIsRotateEnabled) { - //暂不提供手势 - mRotateDetector.onTouchEvent(event); - } + System.out.println(); + //暂不提供手势 + mRotateDetector.onTouchEvent(event); if ((event.getAction() ) == TouchEvent.PRIMARY_POINT_UP) { setImageToWrapCropBounds(); @@ -205,9 +109,8 @@ public class GestureCropImageView extends CropImageView implements Component.Tou private class RotateListener extends RotationGestureDetector.SimpleOnRotationGestureListener { @Override - public boolean onRotation(RotationGestureDetector rotationDetector) { + public void onRotation(RotationGestureDetector rotationDetector) { postRotate(rotationDetector.getAngle(), mMidPntX, mMidPntY); - return true; } } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/view/OverlayView.java b/ucrop/src/main/java/com/yalantis/ucrop/view/OverlayView.java index 10c82e3dffbd8fe1924b27bc8a931e8bbe1114f2..183bb137370fd16d5332a41858db68a53357ad9f 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/view/OverlayView.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/view/OverlayView.java @@ -1,31 +1,21 @@ package com.yalantis.ucrop.view; - - - import com.yalantis.ucrop.callback.OverlayViewChangeListener; import com.yalantis.ucrop.util.Config; import com.yalantis.ucrop.util.LogUtils; import com.yalantis.ucrop.util.RectUtils; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; - - - import ohos.agp.components.AttrSet; import ohos.agp.components.Component; import ohos.agp.render.Canvas; import ohos.agp.render.Paint; import ohos.agp.render.Path; -import ohos.agp.render.Region; import ohos.agp.utils.Color; import ohos.agp.utils.RectFloat; import ohos.app.Context; import ohos.eventhandler.EventHandler; import ohos.eventhandler.EventRunner; import ohos.multimodalinput.event.TouchEvent; -import ohos.utils.Dimension; import static ohos.agp.render.Canvas.ClipOp.DIFFERENCE; import static ohos.agp.render.Canvas.PorterDuffMode.CLEAR; @@ -40,14 +30,8 @@ public class OverlayView extends Component implements Component.DrawTask, Compon public static final int FREESTYLE_CROP_MODE_DISABLE = 0; public static final int FREESTYLE_CROP_MODE_ENABLE = 1; - public static final int FREESTYLE_CROP_MODE_ENABLE_WITH_PASS_THROUGH = 2; - public static final boolean DEFAULT_SHOW_CROP_FRAME = true; - public static final boolean DEFAULT_SHOW_CROP_GRID = true; - public static final boolean DEFAULT_CIRCLE_DIMMED_LAYER = false; public static final int DEFAULT_FREESTYLE_CROP_MODE = FREESTYLE_CROP_MODE_DISABLE; - public static final int DEFAULT_CROP_GRID_ROW_COUNT = 2; - public static final int DEFAULT_CROP_GRID_COLUMN_COUNT = 2; private final RectFloat mCropViewRect = new RectFloat(); private final RectFloat mTempRect = new RectFloat(); @@ -62,17 +46,17 @@ public class OverlayView extends Component implements Component.DrawTask, Compon private boolean mShowCropFrame, mShowCropGrid; private boolean mCircleDimmedLayer; private int mDimmedColor; - private Path mCircularPath = new Path(); - private Paint mDimmedStrokePaint = new Paint(); - private Paint mCropGridPaint = new Paint(); - private Paint mCropFramePaint = new Paint(); - private Paint mCropFrameCornersPaint = new Paint(); + private final Path mCircularPath = new Path(); + private final Paint mDimmedStrokePaint = new Paint(); + private final Paint mCropGridPaint = new Paint(); + private final Paint mCropFramePaint = new Paint(); + private final Paint mCropFrameCornersPaint = new Paint(); private int mFreestyleCropMode = DEFAULT_FREESTYLE_CROP_MODE; private float mPreviousTouchX = -1, mPreviousTouchY = -1; private int mCurrentTouchCornerIndex = -1; - private int mTouchPointThreshold; - private int mCropRectMinSize; - private int mCropRectCornerTouchAreaLineLength; + private final int mTouchPointThreshold; + private final int mCropRectMinSize; + private final int mCropRectCornerTouchAreaLineLength; private OverlayViewChangeListener mCallback; @@ -84,23 +68,11 @@ public class OverlayView extends Component implements Component.DrawTask, Compon mCropRectCornerTouchAreaLineLength = 10; } - public OverlayView(Context context) { - this(context, null); - } - public OverlayView(Context context, AttrSet attrs) { - this(context, attrs, "0"); - } - - public OverlayView(Context context, AttrSet attrs, String defStyle) { - super(context, attrs, defStyle); + super(context, attrs, "0"); init(); } - public OverlayViewChangeListener getOverlayViewChangeListener() { - return mCallback; - } - public void setOverlayViewChangeListener(OverlayViewChangeListener callback) { mCallback = callback; } @@ -111,65 +83,24 @@ public class OverlayView extends Component implements Component.DrawTask, Compon } @Deprecated - /*** - * Please use the new method {@link #getFreestyleCropMode() getFreestyleCropMode} method as we have more than 1 freestyle crop mode. - */ public boolean isFreestyleCropEnabled() { return mFreestyleCropMode == FREESTYLE_CROP_MODE_ENABLE; } @Deprecated - /*** - * Please use the new method {@link #setFreestyleCropMode setFreestyleCropMode} method as we have more than 1 freestyle crop mode. - */ public void setFreestyleCropEnabled(boolean freestyleCropEnabled) { mFreestyleCropMode = freestyleCropEnabled ? FREESTYLE_CROP_MODE_ENABLE : FREESTYLE_CROP_MODE_DISABLE; } - - public int getFreestyleCropMode() { - return mFreestyleCropMode; - } - - public void setFreestyleCropMode( int mFreestyleCropMode) { - this.mFreestyleCropMode = mFreestyleCropMode; - EventHandler eventHandler = new EventHandler( EventRunner.getMainEventRunner()); - eventHandler.postTask(new Runnable() { - @Override - public void run() { - OverlayView.super.invalidate(); - } - });//风险等级2 - - } - /** - * Setter for {@link #mCircleDimmedLayer} variable. * - * @param circleDimmedLayer - set it to true if you want dimmed layer to be an circle - */ - public void setCircleDimmedLayer(boolean circleDimmedLayer) { - mCircleDimmedLayer = circleDimmedLayer; - } - - /** - * Setter for crop grid rows count. - * Resets {@link #mGridPoints} variable because it is not valid anymore. + * @param cropGridRowCount cropGridRowCount */ public void setCropGridRowCount( int cropGridRowCount) { mCropGridRowCount = cropGridRowCount; mGridPoints = null; } - /** - * Setter for crop grid columns count. - * Resets {@link #mGridPoints} variable because it is not valid anymore. - */ - public void setCropGridColumnCount( int cropGridColumnCount) { - mCropGridColumnCount = cropGridColumnCount; - mGridPoints = null; - } - /** * Setter for {@link #mShowCropFrame} variable. * @@ -197,34 +128,6 @@ public class OverlayView extends Component implements Component.DrawTask, Compon mDimmedColor = dimmedColor; } - /** - * Setter for crop frame stroke width - */ - public void setCropFrameStrokeWidth( int width) { - mCropFramePaint.setStrokeWidth(width); - } - - /** - * Setter for crop grid stroke width - */ - public void setCropGridStrokeWidth( int width) { - mCropGridPaint.setStrokeWidth(width); - } - - /** - * Setter for crop frame color - */ - public void setCropFrameColor(int color) { - mCropFramePaint.setColor(new Color(color)); - } - - /** - * Setter for crop grid color - */ - public void setCropGridColor(int color) { - mCropGridPaint.setColor(new Color(color)); - } - /** * This method sets aspect ratio for crop bounds. * @@ -237,12 +140,7 @@ public class OverlayView extends Component implements Component.DrawTask, Compon if (mThisWidth > 0) { setupCropBounds(); EventHandler eventHandler = new EventHandler( EventRunner.getMainEventRunner()); - eventHandler.postTask(new Runnable() { - @Override - public void run() { - OverlayView.super.invalidate(); - } - });//风险等级2 + eventHandler.postTask(OverlayView.super::invalidate);//风险等级2 } else { mShouldSetupCropBounds = true; } @@ -288,30 +186,24 @@ public class OverlayView extends Component implements Component.DrawTask, Compon // if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { // setLayerType(LAYER_TYPE_SOFTWARE, null); // } 风险等级1 - addDrawTask(new DrawTask() { - @Override - public void onDraw(Component component, Canvas canvas) { - drawDimmedLayer(canvas); - drawCropGrid(canvas); - LogUtils.LogInfo("qqqqqqq:","draw OverLayView"); - } + addDrawTask((component, canvas) -> { + drawDimmedLayer(canvas); + drawCropGrid(canvas); + LogUtils.LogInfo("qqqqqqq:","draw OverLayView"); }); - setLayoutRefreshedListener(new LayoutRefreshedListener() { - @Override - public void onRefreshed(Component component) { - component.setLeft(getPaddingLeft()); //风险等级3 - component.setTop(getPaddingTop()); //风险等级3 - component.setRight(getWidth() - getPaddingRight()); //风险等级3 - component.setBottom(getHeight() - getPaddingBottom()); //风险等级3 - LogUtils.LogInfo("qqqqqqq:", getPaddingLeft()+"/"+getPaddingTop()+"/"+component.getRight()+"/"+component.getBottom()); - - mThisWidth = component.getRight()-component.getLeft(); //风险等级3 - mThisHeight = component.getBottom()-component.getTop(); //风险等级3 - - if (mShouldSetupCropBounds) { - mShouldSetupCropBounds = false; - setTargetAspectRatio(mTargetAspectRatio); - } + setLayoutRefreshedListener(component -> { + component.setLeft(getPaddingLeft()); //风险等级3 + component.setTop(getPaddingTop()); //风险等级3 + component.setRight(getWidth() - getPaddingRight()); //风险等级3 + component.setBottom(getHeight() - getPaddingBottom()); //风险等级3 + LogUtils.LogInfo("qqqqqqq:", getPaddingLeft()+"/"+getPaddingTop()+"/"+component.getRight()+"/"+component.getBottom()); + + mThisWidth = component.getRight()-component.getLeft(); //风险等级3 + mThisHeight = component.getBottom()-component.getTop(); //风险等级3 + + if (mShouldSetupCropBounds) { + mShouldSetupCropBounds = false; + setTargetAspectRatio(mTargetAspectRatio); } }); } @@ -331,24 +223,10 @@ public class OverlayView extends Component implements Component.DrawTask, Compon setTargetAspectRatio(mTargetAspectRatio); } } - - - - /** - * Along with image there are dimmed layer, crop bounds and crop guidelines that must be drawn. - */ - - - - - /** - * * The order of the corners is: - * 0------->1 - * ^ | - * | 4 | - * | v - * 3<-------2 + * + * @param touchX touchX + * @param touchY touchY */ private void updateCropViewRect(float touchX, float touchY) { mTempRect.modify(mCropViewRect); @@ -375,12 +253,7 @@ public class OverlayView extends Component implements Component.DrawTask, Compon mCropViewRect.modify(mTempRect); updateGridPoints(); EventHandler eventHandler = new EventHandler( EventRunner.getMainEventRunner()); - eventHandler.postTask(new Runnable() { - @Override - public void run() { - OverlayView.super.invalidate(); - } - });//风险等级2 + eventHandler.postTask(OverlayView.super::invalidate);//风险等级2 } return; } @@ -396,26 +269,20 @@ public class OverlayView extends Component implements Component.DrawTask, Compon if (changeHeight || changeWidth) { updateGridPoints(); EventHandler eventHandler = new EventHandler( EventRunner.getMainEventRunner()); - eventHandler.postTask(new Runnable() { - @Override - public void run() { - OverlayView.super.invalidate(); - } - });//风险等级2 + eventHandler.postTask(OverlayView.super::invalidate);//风险等级2 } } /** - * * The order of the corners in the float array is: - * 0------->1 - * ^ | - * | 4 | - * | v - * 3<-------2 + * getCurrentTouchIndex * - * @return - index of corner that is being dragged + * @param touchX touchX + * @param touchY touchY + * @return CurrentTouchIndex + * @noinspection checkstyle:JavadocMethod */ private int getCurrentTouchIndex(float touchX, float touchY) { + int result = 4; int closestPointIndex = -1; double closestPointDistance = mTouchPointThreshold; for (int i = 0; i < 8; i += 2) { @@ -427,11 +294,7 @@ public class OverlayView extends Component implements Component.DrawTask, Compon } } - if (mFreestyleCropMode == FREESTYLE_CROP_MODE_ENABLE && closestPointIndex < 0 && mCropViewRect.isInclude(touchX, touchY)) { - return 4; - } - -// for (int i = 0; i <= 8; i += 2) { + if (mFreestyleCropMode != FREESTYLE_CROP_MODE_ENABLE || closestPointIndex >= 0 || !mCropViewRect.isInclude(touchX, touchY)) {// for (int i = 0; i <= 8; i += 2) { // // double distanceToCorner; // if (i < 8) { // corners @@ -446,7 +309,10 @@ public class OverlayView extends Component implements Component.DrawTask, Compon // closestPointIndex = i / 2; // } // } - return closestPointIndex; + result = closestPointIndex; + } + + return result; } /** @@ -496,9 +362,7 @@ public class OverlayView extends Component implements Component.DrawTask, Compon mGridPoints[index++] = (mCropViewRect.getWidth() * (((float) i + 1.0f) / (float) (mCropGridColumnCount + 1))) + mCropViewRect.left; mGridPoints[index++] = mCropViewRect.bottom; } - } - if (mGridPoints != null) { canvas.drawLines(mGridPoints, mCropGridPaint); } } @@ -525,10 +389,9 @@ public class OverlayView extends Component implements Component.DrawTask, Compon } /** - * This method extracts all needed values from the styled attributes. - * Those are used to configure the view. + * + * @param a a */ - @SuppressWarnings("deprecation") protected void processStyledAttributes( Config a) { mCircleDimmedLayer = a.getmCircleDimmedLayer(); mDimmedColor = a.getmDimmedColor(); @@ -544,9 +407,9 @@ public class OverlayView extends Component implements Component.DrawTask, Compon } /** - * This method setups Paint object for the crop bounds. + * + * @param a a */ - @SuppressWarnings("deprecation") private void initCropFrameStyle(Config a) { int cropFrameStrokeSize = a.getCropFrameStrokeSize(); int cropFrameColor = a.getCropFrameColor(); @@ -560,9 +423,9 @@ public class OverlayView extends Component implements Component.DrawTask, Compon } /** - * This method setups Paint object for the crop guidelines. + * + * @param a a */ - @SuppressWarnings("deprecation") private void initCropGridStyle( Config a) { int cropGridStrokeSize = a.getCropGridStrokeSize(); int cropGridColor = a.getCropGridColor(); @@ -635,12 +498,4 @@ public class OverlayView extends Component implements Component.DrawTask, Compon return false; } - - - - @Retention(RetentionPolicy.SOURCE) - - public @interface FreestyleMode { - } - } diff --git a/ucrop/src/main/java/com/yalantis/ucrop/view/TransformImageView.java b/ucrop/src/main/java/com/yalantis/ucrop/view/TransformImageView.java index ad85abecb795ef46b9bbb732230362aa92c01cbe..8601b6d7c31759fad5eaa771a0507ff3dfe7599c 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/view/TransformImageView.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/view/TransformImageView.java @@ -9,9 +9,7 @@ import com.yalantis.ucrop.util.LogUtils; import com.yalantis.ucrop.util.RectUtils; import ohos.agp.components.AttrSet; import ohos.agp.components.Component; -import ohos.agp.components.Image; import ohos.agp.components.PositionLayout; -import ohos.agp.components.element.Element; import ohos.agp.render.Canvas; import ohos.agp.render.Paint; import ohos.agp.render.PixelMapHolder; @@ -41,13 +39,10 @@ public class TransformImageView extends PositionLayout implements Component.Layo private static final int RECT_CORNER_POINTS_COORDS = 8; private static final int RECT_CENTER_POINT_COORDS = 2; - private static final int MATRIX_VALUES_COUNT = 9; protected final float[] mCurrentImageCorners = new float[RECT_CORNER_POINTS_COORDS]; protected final float[] mCurrentImageCenter = new float[RECT_CENTER_POINT_COORDS]; - private float[] mMatrixValues = new float[MATRIX_VALUES_COUNT]; - protected Matrix mCurrentImageMatrix = new Matrix(); protected int mThisWidth, mThisHeight; @@ -63,16 +58,10 @@ public class TransformImageView extends PositionLayout implements Component.Layo private String mImageInputPath, mImageOutputPath; private ExifInfo mExifInfo; - private HiLogLabel hiLogLabel = new HiLogLabel(0, 0, TAG); + private final HiLogLabel hiLogLabel = new HiLogLabel(0, 0, TAG); public static final int MSCALE_X = 0; //!< use with getValues/setValues public static final int MSKEW_X = 1; //!< use with getValues/setValues - public static final int MTRANS_X = 2; //!< use with getValues/setValues public static final int MSKEW_Y = 3; //!< use with getValues/setValues - public static final int MSCALE_Y = 4; //!< use with getValues/setValues - public static final int MTRANS_Y = 5; //!< use with getValues/setValues - public static final int MPERSP_0 = 6; //!< use with getValues/setValues - public static final int MPERSP_1 = 7; //!< use with getValues/setValues - public static final int MPERSP_2 = 8; //!< use with getValues/setValues //添加一个全局变量PixelMapHolder用于传递图片,解决鸿蒙操作canvas时图像不变换的问题 public PixelMapHolder mBitmapHolder; @@ -124,37 +113,12 @@ public class TransformImageView extends PositionLayout implements Component.Layo } - public TransformImageView(Context context) { - this(context, null); - } - - public TransformImageView(Context context, AttrSet attrs) { - this(context, attrs, "0"); - } - - public TransformImageView(Context context, AttrSet attrs, String defStyle) { - super(context, attrs, defStyle); + public TransformImageView(Context context, AttrSet attrs, String s) { + super(context, attrs, "0"); + System.out.println(s); init(); } - public void setTransformImageListener(TransformImageListener transformImageListener) { - mTransformImageListener = transformImageListener; - } - -// @Override -// public void setScaleType(Image.ScaleMode scaleType) { -// if (scaleType == ScaleMode.MATRIX) { -// super.setScaleMode(scaleType); -// } else { -// Log.w(TAG, "Invalid ScaleType. Only ScaleType.MATRIX can be used"); -// } -// } - - - public void setMaxBitmapSize(int maxBitmapSize) { - mMaxBitmapSize = maxBitmapSize; - } - public int getMaxBitmapSize() { if (mMaxBitmapSize <= 0) { mMaxBitmapSize = BitmapLoadUtils.calculateMaxBitmapSize(getContext()); @@ -172,12 +136,7 @@ public class TransformImageView extends PositionLayout implements Component.Layo Component fastBitmapDrawable = new FastBitmapDrawable(mContext, bitmap); EventRunner main_runner = EventRunner.getMainEventRunner(); EventHandler main_handler = new EventHandler(main_runner); - main_handler.postTask(new Runnable() { - @Override - public void run() { - addComponent(fastBitmapDrawable); - } - }); + main_handler.postTask(() -> addComponent(fastBitmapDrawable)); } public String getImageInputPath() { @@ -193,10 +152,9 @@ public class TransformImageView extends PositionLayout implements Component.Layo } /** - * This method takes an Uri as a parameter, then calls method to decode it into Bitmap with specified size. * - * @param imageUri - image Uri - * @throws Exception - can throw exception if having problems with decoding Uri or OOM. + * @param imageUri imageUri + * @param outputUri outputUri */ public void setImageUri(Uri imageUri, Uri outputUri) { int maxBitmapSize = getMaxBitmapSize(); @@ -234,7 +192,10 @@ public class TransformImageView extends PositionLayout implements Component.Layo } /** - * This method calculates scale value for given Matrix object. + * getMatrixScale + * + * @param matrix matrix + * @return getMatrixScale */ public float getMatrixScale(Matrix matrix) { return (float) Math.sqrt(Math.pow(getMatrixValue(matrix, MSCALE_X), 2) @@ -249,7 +210,10 @@ public class TransformImageView extends PositionLayout implements Component.Layo } /** - * This method calculates rotation angle for given Matrix object. + * getMatrixAngle + * + * @param matrix matrix + * @return getMatrixAngle */ public float getMatrixAngle(Matrix matrix) { return (float) -(Math.atan2(getMatrixValue(matrix, MSKEW_X), @@ -258,16 +222,13 @@ public class TransformImageView extends PositionLayout implements Component.Layo public void setImageMatrix(Matrix matrix) { - addDrawTask(new DrawTask() { - @Override - public void onDraw(Component component, Canvas canvas) { - canvas.save(); - canvas.setMatrix(matrix); - canvas.drawPixelMapHolder(mBitmapHolder, 0, 0, new Paint()); - canvas.restore(); - float[] a = matrix.getData(); - LogUtils.LogInfo("qqqqqqqq:", "matrix" + Arrays.toString(a)); - } + addDrawTask((component, canvas) -> { + canvas.save(); + canvas.setMatrix(matrix); + canvas.drawPixelMapHolder(mBitmapHolder, 0, 0, new Paint()); + canvas.restore(); + float[] a = matrix.getData(); + LogUtils.LogInfo("qqqqqqqq:", "matrix" + Arrays.toString(a)); }); mCurrentImageMatrix.setMatrix(matrix); updateCurrentImagePoints(); @@ -348,7 +309,7 @@ public class TransformImageView extends PositionLayout implements Component.Layo protected void init() { // setScaleType(ScaleType.MATRIX); this.setLayoutConfig(layoutConfig); - this.setLayoutRefreshedListener(this::onRefreshed); + this.setLayoutRefreshedListener(this); } //android代码,没有ScaleType.MATRIX,风险等级2 @@ -384,23 +345,10 @@ public class TransformImageView extends PositionLayout implements Component.Layo } protected float getMatrixValue(Matrix matrix, int valueIndex) { - mMatrixValues = matrix.getData(); + float[] mMatrixValues = matrix.getData(); return mMatrixValues[valueIndex]; } - /** - * This method logs given matrix X, Y, scale, and angle values. - * Can be used for debug. - */ - @SuppressWarnings("unused") - protected void printMatrix(String logPrefix, Matrix matrix) { - float x = getMatrixValue(matrix, MTRANS_X); - float y = getMatrixValue(matrix, MTRANS_Y); - float rScale = getMatrixScale(matrix); - float rAngle = getMatrixAngle(matrix); - HiLog.debug(hiLogLabel, logPrefix + ": matrix: { x: " + x + ", y: " + y + ", scale: " + rScale + ", angle: " + rAngle + " }"); - } - /** * This method updates current image corners and center points that are stored in * {@link #mCurrentImageCorners} and {@link #mCurrentImageCenter} arrays. diff --git a/ucrop/src/main/java/com/yalantis/ucrop/view/UCropView.java b/ucrop/src/main/java/com/yalantis/ucrop/view/UCropView.java index bbd596dc8cca25dbcbd668e71aa0ececc349c1a5..d24ba0917b55c04da8ba37f672796e003f5557cd 100644 --- a/ucrop/src/main/java/com/yalantis/ucrop/view/UCropView.java +++ b/ucrop/src/main/java/com/yalantis/ucrop/view/UCropView.java @@ -1,33 +1,22 @@ package com.yalantis.ucrop.view; import com.yalantis.ucrop.ResourceTable; -import com.yalantis.ucrop.callback.CropBoundsChangeListener; -import com.yalantis.ucrop.callback.OverlayViewChangeListener; import com.yalantis.ucrop.util.Config; import ohos.agp.components.AttrSet; import ohos.agp.components.ComponentContainer; import ohos.agp.components.LayoutScatter; import ohos.agp.components.StackLayout; -import ohos.agp.utils.RectFloat; import ohos.app.Context; public class UCropView extends StackLayout { StackLayout.LayoutConfig layoutConfig = new StackLayout.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_CONTENT, ComponentContainer.LayoutConfig.MATCH_CONTENT); - private GestureCropImageView mGestureCropImageView; + private final GestureCropImageView mGestureCropImageView; private final OverlayView mViewOverlay; - public UCropView(Context context){ - this(context, null); - } - public UCropView(Context context, AttrSet attrs) { - this(context, attrs, "0"); - } - - public UCropView(Context context, AttrSet attrs, String defStyleAttr) { - super(context, attrs, defStyleAttr); + super(context, attrs, "0"); setLayoutConfig(layoutConfig); @@ -45,26 +34,10 @@ public class UCropView extends StackLayout { } private void setListenersToViews() { - mGestureCropImageView.setCropBoundsChangeListener(new CropBoundsChangeListener() { - @Override - public void onCropAspectRatioChanged(float cropRatio) { - mViewOverlay.setTargetAspectRatio(cropRatio); - } - }); - mViewOverlay.setOverlayViewChangeListener(new OverlayViewChangeListener() { - @Override - public void onCropRectUpdated(RectFloat cropRect) { - mGestureCropImageView.setCropRect(cropRect); - } - }); + mGestureCropImageView.setCropBoundsChangeListener(mViewOverlay::setTargetAspectRatio); + mViewOverlay.setOverlayViewChangeListener(mGestureCropImageView::setCropRect); } -// @Override -// public boolean shouldDelayChildPressedState() { -// return false; -// }//风险等级1 - - public GestureCropImageView getCropImageView() { return mGestureCropImageView; } @@ -73,16 +46,4 @@ public class UCropView extends StackLayout { public OverlayView getOverlayView() { return mViewOverlay; } - - /** - * Method for reset state for UCropImageView such as rotation, scale, translation. - * Be careful: this method recreate UCropImageView instance and reattach it to layout. - */ - public void resetCropImageView() { - removeComponent(mGestureCropImageView); - mGestureCropImageView = new GestureCropImageView(getContext()); - setListenersToViews(); - mGestureCropImageView.setCropRect(getOverlayView().getCropViewRect()); - addComponent(mGestureCropImageView, 0); - } } \ No newline at end of file