Commit 1534c8ea authored by sunzheng's avatar sunzheng

android init

parent c644ae67
package com.reactlibrary;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
public class PicEditActivity extends Activity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String questions = getIntent().getStringExtra("questions");
Log.i("picEdit","拿到入参了哦");
Intent intent=new Intent();
// Response response=new Response(0,"success",questions);
intent.putExtra("result",questions);
setResult(RESULT_OK,intent);
Log.i("picEdit", "将要关闭了哦");
finish();
}
}
package com.reactlibrary;
import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.PopupWindow;
import com.facebook.react.bridge.ActivityEventListener;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.reactlibrary.view.ImageShowActivity;
import java.util.concurrent.ArrayBlockingQueue;
public class PicEditModule extends ReactContextBaseJavaModule {
private ReactApplicationContext mContext;
private View contentView;
private PopupWindow popupWindow;
private static final int REQUEST_CODE = 60000;
//static ArrayBlockingQueue<Response> myBlockingQueue = new ArrayBlockingQueue<Response>(1);
public PicEditModule(ReactApplicationContext context) {
super(context);
//context.addActivityEventListener(this);
this.mContext = context;
}
@Override
public String getName() {
return "PicEditModule";
}
@ReactMethod
public void edit(String json){
Intent intent = new Intent(getCurrentActivity(), ImageShowActivity.class);
intent.putExtra("questions", json);
Log.i("picEdit", "入参"+json);
getCurrentActivity().startActivityForResult(intent, REQUEST_CODE);
}
// @Override
// public void onNewIntent(Intent intent) {
//
// }
// 真正要解决的
// @Override
// public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) {
// Log.i("picEdit", "从图片编辑页退出来啦");
// if (requestCode == REQUEST_CODE) {
// String result = data.getStringExtra("result");
// if (!TextUtils.isEmpty(result)){
// Log.i("picEdit", "顺利拿到数据并封装给js" + result);
// myBlockingQueue.add(new Response(0, "success", result));
// } else {
// myBlockingQueue.add(new Response(-1, "empty data", ""));
// }
// }
// }
// @Override
// public void onCatalystInstanceDestroy() {
// // do nothing
// try{
// myBlockingQueue.clear();
// super.onCatalystInstanceDestroy();
// }catch (Exception ex){
//
// }
// }
// pm的
// @Override
// public void onActivityResult(Activity activity, final int requestCode, final int resultCode, final Intent data) {
// if (requestCode == IMAGE_PICKER_REQUEST) {
// imagePickerResult(activity, requestCode, resultCode, data);
// } else if (requestCode == CAMERA_PICKER_REQUEST) {
// cameraPickerResult(activity, requestCode, resultCode, data);
// } else if (requestCode == UCrop.REQUEST_CROP) {
// croppingResult(activity, requestCode, resultCode, data);
// }
// }
// 我的
}
package com.reactlibrary;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import javax.annotation.Nonnull;
public class PicEditPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
return Arrays.asList(new NativeModule[]{
// Modules from third-party
new PicEditModule(reactContext),
});
}
@Nonnull
@Override
public List<ViewManager> createViewManagers(@Nonnull ReactApplicationContext reactContext) {
//return Arrays.<ViewManager>asList(new TextViewManager());
return Collections.emptyList();
}
}
package com.reactlibrary;
public class Response {
private int code;
private String msg;
private String data;
public Response(int code, String msg, String data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
package com.reactlibrary.photoview;
import android.view.View;
public class Compat {
private static final int SIXTY_FPS_INTERVAL = 1000 / 60;
public static void postOnAnimation(View view, Runnable runnable) {
view.postDelayed(runnable, SIXTY_FPS_INTERVAL);
}
}
/*******************************************************************************
* Copyright 2011, 2012 Chris Banes.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.reactlibrary.photoview;
import android.graphics.RectF;
import android.view.View;
import android.widget.ImageView;
public interface IPhotoView {
/**
* Returns true if the PhotoView is set to allow zooming of Photos.
*
* @return true if the PhotoView allows zooming.
*/
boolean canZoom();
/**
* Gets the Display Rectangle of the currently displayed Drawable. The
* Rectangle is relative to this View and includes all scaling and
* translations.
*
* @return - RectF of Displayed Drawable
*/
RectF getDisplayRect();
/**
* @return The current minimum scale level. What this value represents depends on the current {@link ImageView.ScaleType}.
*/
float getMinScale();
/**
* @return The current middle scale level. What this value represents depends on the current {@link ImageView.ScaleType}.
*/
float getMidScale();
/**
* @return The current maximum scale level. What this value represents depends on the current {@link ImageView.ScaleType}.
*/
float getMaxScale();
/**
* Returns the current scale value
*
* @return float - current scale value
*/
float getScale();
/**
* Return the current scale type in use by the ImageView.
*/
ImageView.ScaleType getScaleType();
/**
* Whether to allow the ImageView's parent to intercept the touch event when the photo is scroll to it's horizontal edge.
*/
void setAllowParentInterceptOnEdge(boolean allow);
/**
* Sets the minimum scale level. What this value represents depends on the current {@link ImageView.ScaleType}.
*/
void setMinScale(float minScale);
/**
* Sets the middle scale level. What this value represents depends on the current {@link ImageView.ScaleType}.
*/
void setMidScale(float midScale);
/**
* Sets the maximum scale level. What this value represents depends on the current {@link ImageView.ScaleType}.
*/
void setMaxScale(float maxScale);
/**
* Register a callback to be invoked when the Photo displayed by this view is long-pressed.
*
* @param listener - Listener to be registered.
*/
void setOnLongClickListener(View.OnLongClickListener listener);
/**
* Register a callback to be invoked when the Matrix has changed for this
* View. An example would be the user panning or scaling the Photo.
*
* @param listener - Listener to be registered.
*/
void setOnMatrixChangeListener(PhotoViewAttacher.OnMatrixChangedListener listener);
/**
* Register a callback to be invoked when the Photo displayed by this View
* is tapped with a single tap.
*
* @param listener - Listener to be registered.
*/
void setOnPhotoTapListener(PhotoViewAttacher.OnPhotoTapListener listener);
/**
* Register a callback to be invoked when the View is tapped with a single
* tap.
*
* @param listener - Listener to be registered.
*/
void setOnViewTapListener(PhotoViewAttacher.OnViewTapListener listener);
/**
* Controls how the image should be resized or moved to match the size of
* the ImageView. Any scaling or panning will happen within the confines of
* this {@link ImageView.ScaleType}.
*
* @param scaleType - The desired scaling mode.
*/
void setScaleType(ImageView.ScaleType scaleType);
/**
* Allows you to enable/disable the zoom functionality on the ImageView.
* When disable the ImageView reverts to using the FIT_CENTER matrix.
*
* @param zoomable - Whether the zoom functionality is enabled.
*/
void setZoomable(boolean zoomable);
/**
* Zooms to the specified scale, around the focal point given.
*
* @param scale - Scale to zoom to
* @param focalX - X Focus Point
* @param focalY - Y Focus Point
*/
void zoomTo(float scale, float focalX, float focalY);
}
package com.reactlibrary.photoview;
import android.content.Context;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.AttributeSet;
import android.widget.ImageView;
public class PhotoView extends ImageView implements IPhotoView {
private final PhotoViewAttacher mAttacher;
private ScaleType mPendingScaleType;
public PhotoView(Context context) {
this(context, null);
}
public PhotoView(Context context, AttributeSet attr) {
this(context, attr, 0);
}
public PhotoView(Context context, AttributeSet attr, int defStyle) {
super(context, attr, defStyle);
super.setScaleType(ScaleType.MATRIX);
mAttacher = new PhotoViewAttacher(this);
if (null != mPendingScaleType) {
setScaleType(mPendingScaleType);
mPendingScaleType = null;
}
}
@Override
public void setOnClickListener(OnClickListener l) {
if (mAttacher != null) mAttacher.setOnClickListener(l);
}
@Override
public boolean canZoom() {
return mAttacher.canZoom();
}
@Override
public RectF getDisplayRect() {
return mAttacher.getDisplayRect();
}
@Override
public float getMinScale() {
return mAttacher.getMinScale();
}
@Override
public float getMidScale() {
return mAttacher.getMidScale();
}
@Override
public float getMaxScale() {
return mAttacher.getMaxScale();
}
@Override
public float getScale() {
return mAttacher.getScale();
}
@Override
public ScaleType getScaleType() {
return mAttacher.getScaleType();
}
@Override
public void setAllowParentInterceptOnEdge(boolean allow) {
mAttacher.setAllowParentInterceptOnEdge(allow);
}
@Override
public void setMinScale(float minScale) {
mAttacher.setMinScale(minScale);
}
@Override
public void setMidScale(float midScale) {
mAttacher.setMidScale(midScale);
}
@Override
public void setMaxScale(float maxScale) {
mAttacher.setMaxScale(maxScale);
}
@Override
// setImageBitmap calls through to this method
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageResource(int resId) {
super.setImageResource(resId);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
if (null != mAttacher) {
mAttacher.update();
}
}
@Override
public void setOnMatrixChangeListener(PhotoViewAttacher.OnMatrixChangedListener listener) {
mAttacher.setOnMatrixChangeListener(listener);
}
@Override
public void setOnLongClickListener(OnLongClickListener l) {
mAttacher.setOnLongClickListener(l);
}
@Override
public void setOnPhotoTapListener(PhotoViewAttacher.OnPhotoTapListener listener) {
mAttacher.setOnPhotoTapListener(listener);
}
@Override
public void setOnViewTapListener(PhotoViewAttacher.OnViewTapListener listener) {
mAttacher.setOnViewTapListener(listener);
}
@Override
public void setScaleType(ScaleType scaleType) {
if (null != mAttacher) {
mAttacher.setScaleType(scaleType);
} else {
mPendingScaleType = scaleType;
}
}
@Override
public void setZoomable(boolean zoomable) {
mAttacher.setZoomable(zoomable);
}
@Override
public void zoomTo(float scale, float focalX, float focalY) {
mAttacher.zoomTo(scale, focalX, focalY);
}
@Override
protected void onDetachedFromWindow() {
mAttacher.cleanup();
super.onDetachedFromWindow();
}
public void clearZoom() {
if (mAttacher.getScale() > PhotoViewAttacher.DEFAULT_MIN_SCALE) {
mAttacher.zoomTo(PhotoViewAttacher.DEFAULT_MIN_SCALE, getWidth() / 2, getHeight() / 2);
}
}
}
\ No newline at end of file
package com.reactlibrary.photoview;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.widget.OverScroller;
import android.widget.Scroller;
public abstract class ScrollerProxy {
public static ScrollerProxy getScroller(Context context) {
if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) {
return new PreGingerScroller(context);
} else {
return new GingerScroller(context);
}
}
public abstract boolean computeScrollOffset();
public abstract void fling(int startX, int startY, int velocityX,
int velocityY, int minX, int maxX, int minY, int maxY, int overX,
int overY);
public abstract void forceFinished(boolean finished);
public abstract int getCurrX();
public abstract int getCurrY();
private static class GingerScroller extends ScrollerProxy {
private OverScroller mScroller;
public GingerScroller(Context context) {
mScroller = new OverScroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY,
int minX, int maxX, int minY, int maxY, int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX,
minY, maxY, overX, overY);
}
@Override
public void forceFinished(boolean finished) {
mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
private static class PreGingerScroller extends ScrollerProxy {
private Scroller mScroller;
public PreGingerScroller(Context context) {
mScroller = new Scroller(context);
}
@Override
public boolean computeScrollOffset() {
return mScroller.computeScrollOffset();
}
@Override
public void fling(int startX, int startY, int velocityX, int velocityY,
int minX, int maxX, int minY, int maxY, int overX, int overY) {
mScroller.fling(startX, startY, velocityX, velocityY, minX, maxX,
minY, maxY);
}
@Override
public void forceFinished(boolean finished) {
mScroller.forceFinished(finished);
}
@Override
public int getCurrX() {
return mScroller.getCurrX();
}
@Override
public int getCurrY() {
return mScroller.getCurrY();
}
}
}
package com.reactlibrary.photoview;
import android.content.Context;
import android.os.Build;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
import android.view.VelocityTracker;
import android.view.ViewConfiguration;
public abstract class VersionedGestureDetector {
static final String LOG_TAG = "VersionedGestureDetector";
OnGestureListener mListener;
public static VersionedGestureDetector newInstance(Context context,
OnGestureListener listener) {
final int sdkVersion = Build.VERSION.SDK_INT;
VersionedGestureDetector detector = null;
if (sdkVersion < Build.VERSION_CODES.ECLAIR) {
detector = new CupcakeDetector(context);
} else if (sdkVersion < Build.VERSION_CODES.FROYO) {
detector = new EclairDetector(context);
} else {
detector = new FroyoDetector(context);
}
detector.mListener = listener;
return detector;
}
public abstract boolean onTouchEvent(MotionEvent ev);
public abstract boolean isScaling();
public static interface OnGestureListener {
public void onDrag(float dx, float dy);
public void onFling(float startX, float startY, float velocityX,
float velocityY);
public void onScale(float scaleFactor, float focusX, float focusY);
}
private static class CupcakeDetector extends VersionedGestureDetector {
float mLastTouchX;
float mLastTouchY;
final float mTouchSlop;
final float mMinimumVelocity;
public CupcakeDetector(Context context) {
final ViewConfiguration configuration = ViewConfiguration
.get(context);
mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
mTouchSlop = configuration.getScaledTouchSlop();
}
private VelocityTracker mVelocityTracker;
private boolean mIsDragging;
float getActiveX(MotionEvent ev) {
return ev.getX();
}
float getActiveY(MotionEvent ev) {
return ev.getY();
}
public boolean isScaling() {
return false;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(ev);
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
mIsDragging = false;
break;
}
case MotionEvent.ACTION_MOVE: {
final float x = getActiveX(ev);
final float y = getActiveY(ev);
final float dx = x - mLastTouchX, dy = y - mLastTouchY;
if (!mIsDragging) {
// Use Pythagoras to see if drag length is larger than
// touch slop
mIsDragging = Math.sqrt((dx * dx) + (dy * dy)) >= mTouchSlop;
}
if (mIsDragging) {
mListener.onDrag(dx, dy);
mLastTouchX = x;
mLastTouchY = y;
if (null != mVelocityTracker) {
mVelocityTracker.addMovement(ev);
}
}
break;
}
case MotionEvent.ACTION_CANCEL: {
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
case MotionEvent.ACTION_UP: {
if (mIsDragging) {
if (null != mVelocityTracker) {
mLastTouchX = getActiveX(ev);
mLastTouchY = getActiveY(ev);
// Compute velocity within the last 1000ms
mVelocityTracker.addMovement(ev);
mVelocityTracker.computeCurrentVelocity(1000);
final float vX = mVelocityTracker.getXVelocity(), vY = mVelocityTracker
.getYVelocity();
// If the velocity is greater than minVelocity, call
// listener
if (Math.max(Math.abs(vX), Math.abs(vY)) >= mMinimumVelocity) {
mListener.onFling(mLastTouchX, mLastTouchY, -vX,
-vY);
}
}
}
// Recycle Velocity Tracker
if (null != mVelocityTracker) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
}
return true;
}
}
private static class EclairDetector extends CupcakeDetector {
private static final int INVALID_POINTER_ID = -1;
private int mActivePointerId = INVALID_POINTER_ID;
private int mActivePointerIndex = 0;
public EclairDetector(Context context) {
super(context);
}
@Override
float getActiveX(MotionEvent ev) {
try {
return ev.getX(mActivePointerIndex);
} catch (Exception e) {
return ev.getX();
}
}
@Override
float getActiveY(MotionEvent ev) {
try {
return ev.getY(mActivePointerIndex);
} catch (Exception e) {
return ev.getY();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
final int action = ev.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mActivePointerId = ev.getPointerId(0);
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
mActivePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_POINTER_UP:
final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = ev.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = ev.getPointerId(newPointerIndex);
mLastTouchX = ev.getX(newPointerIndex);
mLastTouchY = ev.getY(newPointerIndex);
}
break;
}
mActivePointerIndex = ev
.findPointerIndex(mActivePointerId != INVALID_POINTER_ID ? mActivePointerId
: 0);
return super.onTouchEvent(ev);
}
}
private static class FroyoDetector extends EclairDetector {
private final ScaleGestureDetector mDetector;
// Needs to be an inner class so that we don't hit
// VerifyError's on API 4.
private final OnScaleGestureListener mScaleListener = new OnScaleGestureListener() {
@Override
public boolean onScale(ScaleGestureDetector detector) {
mListener.onScale(detector.getScaleFactor(),
detector.getFocusX(), detector.getFocusY());
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
// NO-OP
}
};
public FroyoDetector(Context context) {
super(context);
mDetector = new ScaleGestureDetector(context, mScaleListener);
}
@Override
public boolean isScaling() {
return mDetector.isInProgress();
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
mDetector.onTouchEvent(ev);
return super.onTouchEvent(ev);
}
}
}
\ No newline at end of file
package com.reactlibrary.util;
/**
* Created by huangziwei on 2017/4/11.
*/
public interface CompareRunnable<T> extends Comparable<T>, Runnable {
}
package com.reactlibrary.util;
import android.app.Activity;
import android.app.Dialog;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.reactlibrary.R;
/**
* description:
* create by yuyong on 2019-09-21
*/
public class DialogUtil {
/**
* 显示选择框
*
* @param activity
* @param callBack
* @param editable 是否显示编辑
*/
public static void showEditDialog(Activity activity, boolean editable, final ChooseCallBack callBack) {
final Dialog dialog = new Dialog(activity, R.style.MyDialogStyleBottom);
LayoutInflater inflater = LayoutInflater.from(activity);
final LinearLayout view = (LinearLayout) inflater.inflate(R.layout.dialog_list_down, null);
final TextView tvEdit = view.findViewById(R.id.tv_edit);
view.findViewById(R.id.tv_edit).setVisibility(editable ? View.VISIBLE : View.GONE);
view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
view.findViewById(R.id.tv_edit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
callBack.edit(tvEdit);
}
});
view.findViewById(R.id.tv_save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
callBack.save();
}
});
dialog.setContentView(view);
Window window = dialog.getWindow();
window.setGravity(Gravity.BOTTOM);
window.setWindowAnimations(R.style.topDialogStyle); // 添加动画
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.width = ScreenUtil.getScreenWidth(activity); // 设置宽度
dialog.getWindow().setAttributes(lp);
dialog.show();
}
public interface ChooseCallBack {
void save();
void edit(TextView tvEdit);
}
}
package com.reactlibrary.util;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.FrameLayout;
import com.reactlibrary.util.androids.LogUtil;
/**
* Created by Administrator on 2016/9/3.
*/
public class DrawUtil {
// 涂鸦系统中的单位,根据图片居中时缩放倍数决定。一单位在视觉上的尺寸相同
// public static float DOODLE_PIXEL_UNIT = 1;
public static void drawArrow(Canvas canvas, float sx, float sy, float ex,
float ey, Paint paint) {
float arrowSize = paint.getStrokeWidth();
double H = arrowSize; // 箭头高度
double L = arrowSize / 2; // 底边的一�?
double awrad = Math.atan(L / 2 / H); // 箭头角度
double arraow_len = Math.sqrt(L / 2 * L / 2 + H * H) - 5; // 箭头的长�?
double[] arrXY_1 = rotateVec(ex - sx, ey - sy, awrad, true,
arraow_len);
double[] arrXY_2 = rotateVec(ex - sx, ey - sy, -awrad, true,
arraow_len);
float x_3 = (float) (ex - arrXY_1[0]); // (x3,y3)是第�?端点
float y_3 = (float) (ey - arrXY_1[1]);
float x_4 = (float) (ex - arrXY_2[0]); // (x4,y4)是第二端�?
float y_4 = (float) (ey - arrXY_2[1]);
// 画线
Path linePath = new Path();
linePath.moveTo(sx, sy);
linePath.lineTo(x_3, y_3);
linePath.lineTo(x_4, y_4);
linePath.close();
canvas.drawPath(linePath, paint);
awrad = Math.atan(L / H); // 箭头角度
arraow_len = Math.sqrt(L * L + H * H); // 箭头的长�?
arrXY_1 = rotateVec(ex - sx, ey - sy, awrad, true, arraow_len);
arrXY_2 = rotateVec(ex - sx, ey - sy, -awrad, true, arraow_len);
x_3 = (float) (ex - arrXY_1[0]); // (x3,y3)是第�?端点
y_3 = (float) (ey - arrXY_1[1]);
x_4 = (float) (ex - arrXY_2[0]); // (x4,y4)是第二端�?
y_4 = (float) (ey - arrXY_2[1]);
Path triangle = new Path();
triangle.moveTo(ex, ey);
triangle.lineTo(x_3, y_3);
triangle.lineTo(x_4, y_4);
triangle.close();
canvas.drawPath(triangle, paint);
}
// 计算 向量(px,py) 旋转ang角度后的新长度
public static double[] rotateVec(float px, float py, double ang,
boolean isChLen, double newLen) {
double mathstr[] = new double[2];
// 矢量旋转函数,参数含义分别是x分量、y分量、旋转角、是否改变长度�?�新长度
double vx = px * Math.cos(ang) - py * Math.sin(ang);
double vy = px * Math.sin(ang) + py * Math.cos(ang);
if (isChLen) {
double d = Math.sqrt(vx * vx + vy * vy);
vx = vx / d * newLen;
vy = vy / d * newLen;
}
mathstr[0] = vx;
mathstr[1] = vy;
return mathstr;
}
public static void drawLine(Canvas canvas, float sx, float sy, float dx, float dy, Paint paint) {
canvas.drawLine(sx, sy, dx, dy, paint);
}
public static void drawCircle(Canvas canvas, float cx, float cy, float radius, Paint paint) {
canvas.drawCircle(cx, cy, radius, paint);
}
public static void drawRect(Canvas canvas, float sx, float sy, float dx, float dy, Paint paint) {
// 保证 左上角 与 右下角 的对应关系
if (sx < dx) {
if (sy < dy) {
canvas.drawRect(sx, sy, dx, dy, paint);
} else {
canvas.drawRect(sx, dy, dx, sy, paint);
}
} else {
if (sy < dy) {
canvas.drawRect(dx, sy, sx, dy, paint);
} else {
canvas.drawRect(dx, dy, sx, sy, paint);
}
}
}
/**
* 计算点p2绕p1顺时针旋转的角度
*
* @param px1
* @param py1
* @param px2
* @param py2
* @return 旋转的角度
*/
public static float computeAngle(float px1, float py1, float px2, float py2) {
float x = px2 - px1;
float y = py2 - py1;
float arc = (float) Math.atan(y / x);
float angle = (float) (arc / (Math.PI * 2) * 360);
if (x >= 0 && y == 0) {
angle = 0;
} else if (x < 0 && y == 0) {
angle = 180;
} else if (x == 0 && y > 0) {
angle = 90;
} else if (x == 0 && y < 0) {
angle = 270;
} else if (x > 0 && y > 0) { // 1
} else if (x < 0 && y > 0) { //2
angle = 180 + angle;
} else if (x < 0 && y < 0) { //3
angle = 180 + angle;
} else if (x > 0 && y < 0) { //4
angle = 360 + angle;
}
LogUtil.i("hzw", "[" + px1 + "," + py1 + "]:[" + px2 + "," + py2 + "] = " + angle);
return angle;
}
// 顺时针旋转
public static PointF rotatePoint(PointF coords, float degree, float x, float y, float px, float py) {
if (degree % 360 == 0) {
coords.x = x;
coords.y = y;
return coords;
}
/*角度变成弧度*/
float radian = (float) (degree * Math.PI / 180);
coords.x = (float) ((x - px) * Math.cos(radian) - (y - py) * Math.sin(radian) + px);
coords.y = (float) ((x - px) * Math.sin(radian) + (y - py) * Math.cos(radian) + py);
return coords;
}
public static void main(String[] args) {
/*PointF pointF = new PointF(0,0);
restoreRotatePointInDoodle(pointF,90,0,0,0,100,100);
System.out.printf(pointF.toString());*/
}
public static void assistActivity(Window activity) {
new AndroidBug5497Workaround(activity);
}
public static class AndroidBug5497Workaround {
// For more information, see https://issuetracker.google.com/issues/36911528
// To use this class, simply invoke assistActivity() on an Activity that already has its content view set.
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private AndroidBug5497Workaround(Window window) {
FrameLayout content = (FrameLayout) window.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4)) {
// keyboard probably just became visible
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
} else {
// keyboard probably just became hidden
frameLayoutParams.height = usableHeightSansKeyboard;
}
mChildOfContent.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect r = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(r);
return r.bottom;
}
}
public static void scaleRect(Rect rect, float scale, float px, float py) {
rect.left = (int) (px - scale * (px - rect.left) + 0.5f);
rect.right = (int) (px - scale * (px - rect.right) + 0.5f);
rect.top = (int) (py - scale * (py - rect.top) + 0.5f);
rect.bottom = (int) (py - scale * (py - rect.bottom) + 0.5f);
}
}
package com.reactlibrary.util;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import java.io.IOException;
public class ExifUtils {
public static final String[] EXIF_TAGS = { "FNumber",
ExifInterface.TAG_DATETIME, "ExposureTime",
ExifInterface.TAG_FLASH, ExifInterface.TAG_FOCAL_LENGTH,
"GPSAltitude", "GPSAltitudeRef", ExifInterface.TAG_GPS_DATESTAMP,
ExifInterface.TAG_GPS_LATITUDE, ExifInterface.TAG_GPS_LATITUDE_REF,
ExifInterface.TAG_GPS_LONGITUDE,
ExifInterface.TAG_GPS_LONGITUDE_REF,
ExifInterface.TAG_GPS_PROCESSING_METHOD,
ExifInterface.TAG_GPS_TIMESTAMP, ExifInterface.TAG_IMAGE_LENGTH,
ExifInterface.TAG_IMAGE_WIDTH, "ISOSpeedRatings",
ExifInterface.TAG_MAKE, ExifInterface.TAG_MODEL,
ExifInterface.TAG_WHITE_BALANCE, };
/**
* Return the rotation of the passed image file
*
* @param filepath
* image absolute file path
* @return image orientation
*/
public static int getExifOrientation(final String filepath) {
if (null == filepath)
return 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException e) {
return 0;
}
return getExifOrientation(exif);
}
public static int getExifOrientation(final ExifInterface exif) {
int degree = 0;
if (exif != null) {
final int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
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;
}
}
}
return degree;
}
/**
* Load the exif tags into the passed Bundle
*
* @param filepath
* @param out
* @return true if exif tags are loaded correctly
*/
public static boolean loadAttributes(final String filepath, Bundle out) {
ExifInterface e;
try {
e = new ExifInterface(filepath);
} catch (IOException e1) {
e1.printStackTrace();
return false;
}
for (String tag : EXIF_TAGS) {
out.putString(tag, e.getAttribute(tag));
}
return true;
}
/**
* Store the exif attributes in the passed image file using the TAGS stored
* in the passed bundle
*
* @param filepath
* @param bundle
* @return true if success
*/
public static boolean saveAttributes(final String filepath, Bundle bundle) {
ExifInterface exif;
try {
exif = new ExifInterface(filepath);
} catch (IOException e) {
e.printStackTrace();
return false;
}
for (String tag : EXIF_TAGS) {
if (bundle.containsKey(tag)) {
exif.setAttribute(tag, bundle.getString(tag));
}
}
try {
exif.saveAttributes();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* Return the string representation of the given orientation
*
* @param orientation
* @return
*/
public static String getExifOrientation(int orientation) {
switch (orientation) {
case 0:
return String.valueOf(ExifInterface.ORIENTATION_NORMAL);
case 90:
return String.valueOf(ExifInterface.ORIENTATION_ROTATE_90);
case 180:
return String.valueOf(ExifInterface.ORIENTATION_ROTATE_180);
case 270:
return String.valueOf(ExifInterface.ORIENTATION_ROTATE_270);
default:
throw new AssertionError("invalid: " + orientation);
}
}
/**
* Try to get the exif orientation of the passed image uri
*
* @param context
* @param uri
* @return
*/
public static int getExifOrientation(Context context, Uri uri) {
final String scheme = uri.getScheme();
ContentProviderClient provider = null;
if (scheme == null || ContentResolver.SCHEME_FILE.equals(scheme)) {
return getExifOrientation(uri.getPath());
} else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
try {
provider = context.getContentResolver()
.acquireContentProviderClient(uri);
} catch (SecurityException e) {
return 0;
}
if (provider != null) {
Cursor result;
try {
result = provider.query(uri, new String[] {
Images.ImageColumns.ORIENTATION,
Images.ImageColumns.DATA }, null, null, null);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
if (result == null) {
return 0;
}
int orientationColumnIndex = result
.getColumnIndex(Images.ImageColumns.ORIENTATION);
int dataColumnIndex = result
.getColumnIndex(Images.ImageColumns.DATA);
try {
if (result.getCount() > 0) {
result.moveToFirst();
int rotation = 0;
if (orientationColumnIndex > -1) {
rotation = result.getInt(orientationColumnIndex);
}
if (dataColumnIndex > -1) {
String path = result.getString(dataColumnIndex);
rotation |= getExifOrientation(path);
}
return rotation;
}
} finally {
result.close();
}
}
}
return 0;
}
}
This diff is collapsed.
package com.reactlibrary.util.Glide;
import android.content.Context;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.io.File;
/**
* Glide加载图片的工具类
* Created by yuyong on 2019/09/17.
*/
public class GlideImageManager {
/**
* 加载圆形图片
*
* @param context
* @param url
* @param iv
* @param errorImgResId
*/
public static void loadCircleImage(Context context, String url, ImageView iv, int errorImgResId) {
RequestOptions requestOptions = RequestOptions.circleCropTransform()
.placeholder(errorImgResId)
.error(errorImgResId)
.dontAnimate();
Glide.with(context).load(url).apply(requestOptions).into(iv);
}
/**
* 加载圆角图片
*
* @param context
* @param url
* @param iv
* @param round
* @param errorImgResId
*/
public static void loadRoundCornerImage(Context context, String url, final ImageView iv, int round, int errorImgResId) {
Glide.with(context.getApplicationContext())
.load(url)
.apply(new RequestOptions()
.transform(new GlideRoundTransform(context, round))
.placeholder(errorImgResId)
.error(errorImgResId)
.dontAnimate())
.into(iv);
}
/**
* 加载文件路径图片
*
* @param context
* @param file
* @param imageView
*/
public static void loadImage(Context context, final File file, final ImageView imageView, int round, int errorImgResId) {
Glide.with(context.getApplicationContext())
.load(file)
.into(imageView);
}
/**
* 加载本地图片
*
* @param context
* @param resourceId
* @param imageView
*/
public static void loadImage(Context context, final int resourceId, final ImageView imageView, int round) {
Glide.with(context.getApplicationContext())
.load(resourceId)
.apply(new RequestOptions()
.transform(new GlideRoundTransform(context, round))).into(imageView);
}
}
package com.reactlibrary.util.Glide;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.load.resource.bitmap.TransformationUtils;
import java.security.MessageDigest;
/**
* Created by CLOUD on 2016/10/14. glide圆角转换类
*/
public class GlideRoundTransform extends BitmapTransformation {
private static float radius = 0f;
public GlideRoundTransform(Context context) {
this(context, 4);
}
public GlideRoundTransform(Context context, int dp) {
super();
this.radius = Resources.getSystem().getDisplayMetrics().density * dp;
}
@Override
protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
Bitmap bitmap = TransformationUtils.centerCrop(pool, toTransform, outWidth, outHeight);
return roundCrop(pool, bitmap);
}
private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
if (source == null) return null;
Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
if (result == null) {
result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
paint.setAntiAlias(true);
RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
canvas.drawRoundRect(rectF, radius, radius, paint);
return result;
}
public String getId() {
return getClass().getName() + Math.round(radius);
}
@Override
public void updateDiskCacheKey(MessageDigest messageDigest) {
}
}
package com.reactlibrary.util.Glide.Glide_Https;//package com.yuyong.picedit.util.Glide;
//
//import android.app.ActivityManager;
//import android.content.Context;
//
//import com.bumptech.glide.Glide;
//import com.bumptech.glide.GlideBuilder;
//import com.bumptech.glide.Registry;
//import com.bumptech.glide.annotation.GlideModule;
//import com.bumptech.glide.integration.okhttp3.OkHttpUrlLoader;
//import com.bumptech.glide.load.model.GlideUrl;
//import com.bumptech.glide.module.AppGlideModule;
//
//import java.io.InputStream;
//import java.security.cert.CertificateException;
//import java.util.concurrent.TimeUnit;
//
//import javax.net.ssl.HostnameVerifier;
//import javax.net.ssl.SSLContext;
//import javax.net.ssl.SSLSession;
//import javax.net.ssl.SSLSocketFactory;
//import javax.net.ssl.TrustManager;
//import javax.net.ssl.X509TrustManager;
//
//import okhttp3.OkHttpClient;
//
///**
// * description:
// * create by yuyong on 2019-09-20
// */
//@GlideModule
//public class HttpsGlideModule extends AppGlideModule {
//
// @Override
// public void applyOptions(Context context, GlideBuilder builder) {
// ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
// /* if (activityManager != null) {
// builder.setDefaultRequestOptions(ImageUtil.getOption());
// }*/
// }
//
//
// @Override
// public void registerComponents(Context context, Glide glide, Registry registry) {
// //设置请求方式为okhttp 并设置okhttpClient的证书及超时时间
// OkHttpUrlLoader.Factory factory = new OkHttpUrlLoader.Factory(UnsafeOkHttpClient.getUnsafeOkHttpClient());
// registry.replace(GlideUrl.class, InputStream.class, factory);
// }
//
// //自定义工具类修改OkHttpClient证书和超时时间
// static class UnsafeOkHttpClient {
// public static OkHttpClient getUnsafeOkHttpClient() {
// try {
// // Create a trust manager that does not validate certificate chains
// final TrustManager[] trustAllCerts = new TrustManager[]{
// new X509TrustManager() {
// @Override
// public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
// }
//
// @Override
// public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
// }
//
// @Override
// public java.security.cert.X509Certificate[] getAcceptedIssuers() {
// return new java.security.cert.X509Certificate[]{};
// }
// }
// };
//
// // Install the all-trusting trust manager
// final SSLContext sslContext = SSLContext.getInstance("SSL");
// sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
//
// // Create an ssl socket factory with our all-trusting manager
// final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
//
// OkHttpClient.Builder builder = new OkHttpClient.Builder();
// builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
// builder.hostnameVerifier(new HostnameVerifier() {
// @Override
// public boolean verify(String hostname, SSLSession session) {
// return true;
// }
// });
//
// builder.connectTimeout(20, TimeUnit.SECONDS);
// builder.readTimeout(20, TimeUnit.SECONDS);
// builder.writeTimeout(20, TimeUnit.SECONDS);
//
// OkHttpClient okHttpClient = builder.build();
// return okHttpClient;
// } catch (Exception e) {
// throw new RuntimeException(e);
// }
// }
// /**
// * 禁止解析Manifest文件
// * 主要针对V3升级到v4的用户,可以提升初始化速度,避免一些潜在错误
// * @return
// */
// /* @Override
// public boolean isManifestParsingEnabled() {
// return false;
// }*/
// }
//}
//
//
package com.reactlibrary.util.Glide;
import android.graphics.Bitmap;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.bumptech.glide.request.target.ImageViewTarget;
/**
* Created by yuyong on 2019/1/25.
*/
public class TransformationUtils extends ImageViewTarget<Bitmap> {
private ImageView target;
public TransformationUtils(ImageView target) {
super(target);
this.target = target;
}
@Override
protected void setResource(Bitmap resource) {
view.setImageBitmap(resource);
//获取原图的宽高
int width = resource.getWidth();
int height = resource.getHeight();
//获取imageView的宽
int imageViewWidth = target.getWidth();
//计算缩放比例
float sy = (float) (imageViewWidth * 0.1) / (float) (width * 0.1);
//计算图片等比例放大后的高
int imageViewHeight = (int) (height * sy);
ViewGroup.LayoutParams params = target.getLayoutParams();
params.height = imageViewHeight;
target.setLayoutParams(params);
}
}
package com.reactlibrary.util;
public interface IDisposable {
void dispose();
}
package com.reactlibrary.util;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore.Images.ImageColumns;
import java.io.Closeable;
/**
* Various I/O utilities
*
* @author alessandro
*
*/
public class IOUtils {
/**
* Close a {@link Closeable} stream without throwing any exception
*
* @param c
*/
public static void closeSilently( final Closeable c ) {
if ( c == null ) return;
try {
c.close();
} catch ( final Throwable t ) {}
}
public static void closeSilently( final ParcelFileDescriptor c ) {
if ( c == null ) return;
try {
c.close();
} catch ( final Throwable t ) {}
}
public static void closeSilently( Cursor cursor ) {
if ( cursor == null ) return;
try {
if ( cursor != null ) cursor.close();
} catch ( Throwable t ) {}
}
/**
* Try to return the absolute file path from the given Uri
*
* @param context
* @param uri
* @return the file path or null
*/
public static String getRealFilePath( final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
}
package com.reactlibrary.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
public class ImageUtil {
/**
* Drawable转换成一个Bitmap
*
* @param drawable drawable对象
* @return
*/
public static final Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
}
package com.reactlibrary.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;
/**
* description:
* create by yuyong on 2019-09-22
*/
public class LruCacheUtils {
//申明内存缓存
private LruCache<String, Bitmap> mLruCache;
//在构造方法中进行初使化
public LruCacheUtils(Context context) {
//得到当前应用程序的内存
int maxMemory = (int) Runtime.getRuntime().maxMemory();
//内存缓存为当前应用程序的8分之1
int cacheMemory = maxMemory / 8;
//进行初使化
mLruCache = new LruCache<String, Bitmap>(cacheMemory) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();//自定义bitmap数据大小的计算方式
}
};
}
/**
* 保存图片到内存缓存
*
* @param key 图片的url
* @param bitmap 图片
*/
public void savePicToMemory(String key, Bitmap bitmap) {
try {
mLruCache.put(key, bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通过key值得到缓存的图片
*
* @param key 图片的url地址
* @return Bitmap 或 null
*/
public Bitmap getPicFromMemory(String key) {
Bitmap bitmap = null;
try {
//通过key获取图片
bitmap = mLruCache.get(key);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 清除缓存
* evict:驱逐 逐出
*/
public void clearCache() {
if (mLruCache != null) {
if (mLruCache.size() > 0) {
Log.d("CacheUtils",
"mMemoryCache.size() " + mLruCache.size());
mLruCache.evictAll();
Log.d("CacheUtils", "mMemoryCache.size()" + mLruCache.size());
}
mLruCache = null;
}
}
}
/*
* Copyright 2013, Edmodo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work except in compliance with the License.
* You may obtain a copy of the License in the LICENSE file, or at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package com.reactlibrary.util;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.TypedValue;
/**
* Utility class for handling all of the Paint used to draw the CropOverlayView.
*/
public class PaintUtil {
// Private Constants ///////////////////////////////////////////////////////
private static final int DEFAULT_CORNER_COLOR = Color.WHITE;
private static final String SEMI_TRANSPARENT = "#AAFFFFFF";
private static final String DEFAULT_BACKGROUND_COLOR_ID = "#B0000000";
private static final float DEFAULT_LINE_THICKNESS_DP = 3;
private static final float DEFAULT_CORNER_THICKNESS_DP = 5;
private static final float DEFAULT_GUIDELINE_THICKNESS_PX = 1;
// Public Methods //////////////////////////////////////////////////////////
/**
* Creates the Paint object for drawing the crop window border.
*
* @param context
* the Context
* @return new Paint object
*/
public static Paint newBorderPaint(Context context) {
// Set the line thickness for the crop window border.
final float lineThicknessPx = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, DEFAULT_LINE_THICKNESS_DP, context
.getResources().getDisplayMetrics());
final Paint borderPaint = new Paint();
borderPaint.setColor(Color.parseColor(SEMI_TRANSPARENT));
borderPaint.setStrokeWidth(lineThicknessPx);
borderPaint.setStyle(Paint.Style.STROKE);
return borderPaint;
}
/**
* Creates the Paint object for drawing the crop window guidelines.
*
* @return the new Paint object
*/
public static Paint newGuidelinePaint() {
final Paint paint = new Paint();
paint.setColor(Color.parseColor(SEMI_TRANSPARENT));
paint.setStrokeWidth(DEFAULT_GUIDELINE_THICKNESS_PX);
return paint;
}
/**
* Creates the Paint object for drawing the crop window guidelines.
*
* @return the new Paint object
*/
public static Paint newRotateBottomImagePaint() {
final Paint paint = new Paint();
paint.setColor(Color.WHITE);
paint.setStrokeWidth(3);
return paint;
}
/**
* Creates the Paint object for drawing the translucent overlay outside the
* crop window.
*
* @param context
* the Context
* @return the new Paint object
*/
public static Paint newBackgroundPaint(Context context) {
final Paint paint = new Paint();
paint.setColor(Color.parseColor(DEFAULT_BACKGROUND_COLOR_ID));
return paint;
}
/**
* Creates the Paint object for drawing the corners of the border
*
* @param context
* the Context
* @return the new Paint object
*/
public static Paint newCornerPaint(Context context) {
// Set the line thickness for the crop window border.
final float lineThicknessPx = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, DEFAULT_CORNER_THICKNESS_DP,
context.getResources().getDisplayMetrics());
final Paint cornerPaint = new Paint();
cornerPaint.setColor(DEFAULT_CORNER_COLOR);
cornerPaint.setStrokeWidth(lineThicknessPx);
cornerPaint.setStyle(Paint.Style.STROKE);
return cornerPaint;
}
/**
* Returns the value of the corner thickness
*
* @return Float equivalent to the corner thickness
*/
public static float getCornerThickness() {
return DEFAULT_CORNER_THICKNESS_DP;
}
/**
* Returns the value of the line thickness of the border
*
* @return Float equivalent to the line thickness
*/
public static float getLineThickness() {
return DEFAULT_LINE_THICKNESS_DP;
}
}
package com.reactlibrary.util;
public enum Priority {
UI_TOP,
UI_NORMAL,
UI_LOW,
DEFAULT,
BG_TOP,
BG_NORMAL,
BG_LOW,
}
package com.reactlibrary.util;
/**
* Created by huangziwei on 2017/3/30.
*/
public class PriorityRunnable implements CompareRunnable<PriorityRunnable> {
private final Priority mPriority;
private final Runnable mRunnable;
public PriorityRunnable(Priority priority) {
this(priority, null);
}
public PriorityRunnable(Priority priority, Runnable runnable) {
mPriority = priority == null ? Priority.DEFAULT : priority;
mRunnable = runnable;
}
@Override
public int compareTo(PriorityRunnable another) {
if (this.mPriority.ordinal() < another.mPriority.ordinal()) {
return -1;
} else if (this.mPriority.ordinal() > another.mPriority.ordinal()) {
return 1;
} else {
return 0;
}
}
@Override
public void run() {
if (mRunnable != null) {
mRunnable.run();
}
}
}
package com.reactlibrary.util;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
/**
* Created by yuyong on 2018/7/16.
*/
public class ScreenUtil {
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
public static int dip2px(Context context, float dipValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dipValue * scale + 0.5f);
}
/**
* 获得屏幕宽度
*
* @param context
* @return
*/
public static int getScreenWidth(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.widthPixels;
}
public static int getScreenWidthdp(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; // 屏幕宽度(像素)
int height = dm.heightPixels; // 屏幕高度(像素)
float density = dm.density; // 屏幕密度(0.75 / 1.0 / 1.5)
int densityDpi = dm.densityDpi; // 屏幕密度dpi(120 / 160 / 240)
// 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
int screenWidth = (int) (width / densityDpi); // 屏幕宽度(dp)
return screenWidth;
}
public static int getScreenHeightdp(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics dm = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels; // 屏幕宽度(像素)
int height = dm.heightPixels; // 屏幕高度(像素)
float density = dm.density; // 屏幕密度(0.75 / 1.0 / 1.5)
int densityDpi = dm.densityDpi; // 屏幕密度dpi(120 / 160 / 240)
// 屏幕宽度算法:屏幕宽度(像素)/屏幕密度
int screenHeight = (int) (height / densityDpi);// 屏幕高度(dp)
return screenHeight;
}
/**
* 获得屏幕高度
*
* @param context
* @return
*/
public static int getScreenHeight(Context context) {
WindowManager wm = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
DisplayMetrics outMetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(outMetrics);
return outMetrics.heightPixels;
}
/**
* 获得状态栏的高度
*
* @param context
* @return
*/
public static int getStatusHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen.xml");
Object object = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height")
.get(object).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (Exception e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 获取当前屏幕截图,包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
view.destroyDrawingCache();
return bp;
}
/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity
* @return
*/
public static Bitmap snapShotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap bp = null;
bp = Bitmap.createBitmap(bmp, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return bp;
}
}
package com.reactlibrary.util;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
/**
* description:发送消息给js
* create by yuyong on 2019-09-24
*/
public class SendEventToJsUtil {
//定义上下文对象
public ReactContext myContext;
public SendEventToJsUtil(ReactContext context) {
this.myContext = context;
}
//定义发送事件的函数
public void sendEventToJs(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
}
/**
* 发送消息
*
* @param eventName 事件名称
* @param key 传值key
* @param content 传值value
*/
public void sendMsg(String eventName, String key, String content) {
//发送事件,事件名为EventName
WritableMap wm = Arguments.createMap();
wm.putString(key, content);
sendEventToJs(myContext, eventName, wm);
}
}
package com.reactlibrary.util.androids;
import android.graphics.Color;
/**
* 颜色工具栏
*
* @author hzw
* @date 2016/1/24.
*/
public class ColorUtil {
/**
* 计算渐变后的颜色
*
* @param startColor 开始颜色
* @param endColor 结束颜色
* @param rate 渐变率(0,1)
* @return 渐变后的颜色,当rate=0时,返回startColor,当rate=1时返回endColor
*/
public static int computeGradientColor(int startColor, int endColor, float rate) {
if (rate < 0) {
rate = 0;
}
if (rate > 1) {
rate = 1;
}
int alpha = Color.alpha(endColor) - Color.alpha(startColor);
int red = Color.red(endColor) - Color.red(startColor);
int green = Color.green(endColor) - Color.green(startColor);
int blue = Color.blue(endColor) - Color.blue(startColor);
return Color.argb(
Math.round(Color.alpha(startColor) + alpha * rate),
Math.round(Color.red(startColor) + red * rate),
Math.round(Color.green(startColor) + green * rate),
Math.round(Color.blue(startColor) + blue * rate));
}
}
package com.reactlibrary.util.androids;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
/**
* 日期工具类
*
* @author huangziwei
* @date 2016.1.13
*/
public class DateUtil {
public final static int DAY = 86400000; //1天=24*60*60*1000ms
public final static int HOUR = 3600000;
public final static int MIN = 60000;
/**
* 获取某个月份的天数
* @param year
* @param month
* @return
*/
public static int getMonthDays(int year, int month) {
if (month > 12) {
month = 1;
year += 1;
} else if (month < 1) {
month = 12;
year -= 1;
}
int[] arr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int days = 0;
if (isLeapYear(year)) {
arr[1] = 29; // 闰年2月29天
}
try {
days = arr[month - 1];
} catch (Exception e) {
e.getStackTrace();
}
return days;
}
/**
* 是否为闰年
*
* @param year
* @return
*/
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
/**
* 根据年份和月份获取日期数组,1、2、3...
*
* @param year
* @param month
* @return
*/
public static List<String> getMonthDaysArray(int year, int month) {
List<String> dayList = new ArrayList<String>();
int days = DateUtil.getMonthDays(year, month);
for (int i = 1; i <= days; i++) {
dayList.add(i + "");
}
return dayList;
}
/**
* 获取当前系统时间的年份
*
* @return
*/
public static int getYear() {
return Calendar.getInstance().get(Calendar.YEAR);
}
/**
* 获取当前系统时间的月份
*
* @return
*/
public static int getMonth() {
return Calendar.getInstance().get(Calendar.MONTH) + 1;
}
/**
* 获取当前系统时间的月份的第几天
*
* @return
*/
public static int getCurrentMonthDay() {
return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
}
/**
* 获取当前系统时间的小时数
*
* @return
*/
public static int getHour() {
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
/**
* 获取当前系统时间的分钟数
*
* @return
*/
public static int getMinute() {
return Calendar.getInstance().get(Calendar.MINUTE);
}
/**
* 获取当前系统时间的秒数
*
* @return
*/
public static int getSecond() {
return Calendar.getInstance().get(Calendar.SECOND);
}
/**
* 获取当前系统时间的毫秒数
*
* @return
*/
public static int getMillSecond() {
return Calendar.getInstance().get(Calendar.MILLISECOND);
}
/**
* 根据系统默认时区,获取当前时间与time的天数差
*
* @param time 相差的天数
* @return 等于0表示今天,大于0表示今天之前
*/
public static long getDaySpan(long time) {
return getTimeSpan(time, DAY);
}
public static long getHourSpan(long time) {
return getTimeSpan(time, HOUR);
}
public static long getMinSpan(long time) {
return getTimeSpan(time, MIN);
}
public static long getTimeSpan(long time, long span) {
// 系统默认时区,ms
int tiemzone = TimeZone.getDefault().getRawOffset();
return (System.currentTimeMillis() + tiemzone) / span
- (time + tiemzone) / span;
}
public static boolean isToday(long time) {
return getDaySpan(time) == 0;
}
public static boolean isYestoday(long time) {
return getDaySpan(time) == 1;
}
public static boolean isTomorrow(long time) {
return getDaySpan(time) == -1;
}
/**
* @return 返回当前时间,yyyy-MM-dd HH-mm-ss
*/
public static String getDate() {
return getDate("yyyy-MM-dd HH-mm-ss");
}
public static String getDate(String format) {
return getDate(new java.util.Date().getTime(), format);
}
public static String getDate(long time, String format) {
SimpleDateFormat sDateFormat = new SimpleDateFormat(format);
String date = sDateFormat.format(time);
return date;
}
}
\ No newline at end of file
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment