SimpleDraweeView в Canvas не отображается - PullRequest
0 голосов
/ 25 апреля 2020

Привет, я пытаюсь нарисовать вид радара с пользовательскими предметами на нем. Пользовательский вид состоит из фонового изображения и изображения пользователя. Оба являются динамическими c. Мне удалось нарисовать радар, но мои компоненты изображения не отображаются. URL-адреса изображений загружаются на других экранах проекта, кроме здесь. Даже фоновое изображение меняется в зависимости от состояния, но пользовательское изображение не показывает

    public class VRORadarView extends View {

    public final static double AVERAGE_RADIUS_OF_EARTH_METERS = 6371000;
    private int radarColor = Color.parseColor("#99a2a2a2");
    private final String LOG_TAG = VRORadarView.class.getName();
    private final int POINT_ARRAY_SIZE = 50;
    float alpha = 0;
    Point latestPoint[] = new Point[POINT_ARRAY_SIZE];
    Paint latestPaint[] = new Paint[POINT_ARRAY_SIZE];
    ArrayList<UserPoints> userPointsArrayList = new ArrayList<>();
    double range;
    int diff;
    private Matrix matrix;

    private int start;
    private int centerX;
    private int centerY;
    private int radarRadius;
    private Paint mPaintRadar;

    private int fps = 100;
    private boolean showCircles = true;
    private LocationPinClickListener pinClickListener;

    public VRORadarView(Context context) {
        this(context, null);
    }

    public VRORadarView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public VRORadarView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);


        Paint localPaint = new Paint();
        localPaint.setColor(Color.rgb(0, 255, 0));
        localPaint.setAntiAlias(true);
        localPaint.setStyle(Style.FILL_AND_STROKE);
        localPaint.setStrokeWidth(3.0F);
        localPaint.setAlpha(0);

        int alpha_step = 255 / (POINT_ARRAY_SIZE);
        for (int i = 0; i < latestPaint.length; i++) {
            latestPaint[i] = new Paint(localPaint);
            latestPaint[i].setAlpha(255 - (i * alpha_step));
        }
        diff = (int) getResources().getDimension(R.dimen.m_margin_15);

        mPaintRadar = new Paint();
        mPaintRadar.setColor(radarColor);
        mPaintRadar.setAntiAlias(true);


    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(measureWidth(widthMeasureSpec),
                measureHeight(heightMeasureSpec));
    }

    /**
     * Determines the width of this view
     * @param measureSpec A measureSpec packed into an int
     * @return The width of the view, honoring constraints from measureSpec
     */
    private int measureWidth(int measureSpec) {
        int result = 0;
        //This is because of background image in relativeLayout, which is 1000*1000px
        measureSpec = 1001;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.UNSPECIFIED) {
            // We were told how big to be
            result = specSize;
        }

        return result;
    }

    /**
     * Determines the height of this view
     * @param measureSpec A measureSpec packed into an int
     * @return The height of the view, honoring constraints from measureSpec
     */
    private int measureHeight(int measureSpec) {
        int result = 0;
        //This is because of background image in relativeLayout, which is 1000*1000px
        measureSpec = 1001;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);


        if (specMode == MeasureSpec.UNSPECIFIED) {
            // Here we say how Heigh to be
            result = specSize;
        }
        return result;
    }


    android.os.Handler mHandler = new android.os.Handler();
    Runnable mTick = new Runnable() {
        @Override
        public void run() {

            if (showCircles) {
                start += 2;
                matrix = new Matrix();
                matrix.postRotate(start, centerX, centerY);
            }

            invalidate();
            mHandler.postDelayed(this, (long) 1000 / fps);
        }
    };


    public void setPinClickListener(LocationPinClickListener pinClickListener) {
        this.pinClickListener = pinClickListener;
    }

    public void startAnimation() {
        mHandler.removeCallbacks(mTick);
        mHandler.post(mTick);
    }

    public void stopAnimation() {
        mHandler.removeCallbacks(mTick);
    }

    public int getFrameRate() {
        return this.fps;
    }

    public void setFrameRate(int fps) {
        this.fps = fps;
    }

    public void setShowCircles(boolean showCircles) {
        this.showCircles = showCircles;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int height = getHeight();

        centerX = width / 2;
        centerY = height / 2;
        radarRadius = Math.min(width, height);

        int r = Math.min(width, height);


        int i = r / 2;
        int j = i - 1;
        Point userCenterPoint = new Point();
        userCenterPoint.x = i;
        userCenterPoint.y = j;


        /*to convert range to meters*/
        if (range >= 1.0 && range <= 5.0) {
            range = range * 1000;

        }

        // GREEN
        Paint localPaint = latestPaint[0];

        localPaint.setColor(Color.rgb(0, 100, 0));
        localPaint.setAntiAlias(true);
        localPaint.setStyle(Style.FILL_AND_STROKE);
        localPaint.setStrokeWidth(1.0F);
        localPaint.setShader(new RadialGradient(i, j, r, Color.rgb(0, 195, 244), Color.rgb(0, 195, 244), Shader.TileMode.MIRROR));
        localPaint.setAlpha(255);

        if (showCircles) {

            canvas.drawCircle(i, i, j, localPaint);
            localPaint.setShader(null);

            localPaint.setColor(Color.rgb(255, 255, 255));
            localPaint.setStyle(Style.STROKE);
            localPaint.setAlpha(80);


            canvas.drawCircle(i, i, j, localPaint);
            canvas.drawCircle(i, i, j, localPaint);
            canvas.drawCircle(i, i, j / 4, localPaint);
            canvas.drawCircle(i, i, j * 3 / 4, localPaint);
            canvas.drawCircle(i, i, j >> 1, localPaint);
            canvas.drawCircle(i, i, j >> 2, localPaint);



            /*trying to draw cross */
            {
                double radius = i;
                canvas.drawLine(i, i, i + 300, i, localPaint);
                canvas.drawLine(i, i, i - 300, i, localPaint);
                canvas.drawLine(i, i, i, i + 300, localPaint);
                canvas.drawLine(i, i, i, i - 300, localPaint);

            }
            localPaint.setStyle(Style.FILL_AND_STROKE);
            localPaint.setAlpha(255);
            canvas.drawCircle(i, i, 8, localPaint);



            /*till here we draw the circle and fill them up and we mark the center also*/


            alpha -= 0.5;
            if (alpha < -360) alpha = 0;
            double angle = Math.toRadians(alpha);
            int offsetX = (int) (i + (float) (i * Math.cos(angle)));
            int offsetY = (int) (i - (float) (i * Math.sin(angle)));

            latestPoint[0] = new Point(offsetX, offsetY);

            for (int x = POINT_ARRAY_SIZE - 1; x > 0; x--) {
                latestPoint[x] = latestPoint[x - 1];
            }


            Shader shader = new SweepGradient(centerX, centerY, Color.parseColor("#00FFFFFF"), Color.parseColor("#95FFFFFF"));
            mPaintRadar.setShader(shader);
            canvas.concat(matrix);
            canvas.drawCircle(centerX, centerY, j, mPaintRadar);


            boolean debug = false;
            if (debug) {
                StringBuilder sb = new StringBuilder(" >> ");
                for (Point p : latestPoint) {
                    if (p != null) sb.append(" (" + p.x + "x" + p.y + ")");
                }

                Log.d(LOG_TAG, sb.toString());
            }


        } else {



             /*now we need to draw other users*/
            double pro = (double) j / range;

            localPaint.setStyle(Style.FILL_AND_STROKE);
            localPaint.setColor(Color.BLUE);
            int myPosition = 0;
            double scaleFactor = 0;


            for (int a = 0; a < userPointsArrayList.size(); a++) {

                myPosition = userPointsArrayList.size() - 1;

                 /*we are scaling the points to spread over the view w.r.t the largest distance in the current list*/
                scaleFactor = j / (userPointsArrayList.get(0).getDistance() * 1000 * pro);
                scaleFactor = scaleFactor * 0.8;

                if (a == myPosition) continue;
                else {
                    double angle = getAngle(userPointsArrayList.get(myPosition), userPointsArrayList.get(a));

                    double distance = calculateDistanceInMeter(userPointsArrayList.get(myPosition).userXLatPoint, userPointsArrayList.get(myPosition).userYLonPoint, userPointsArrayList.get(a).userXLatPoint, userPointsArrayList.get(a).userYLonPoint);
                    distance = (distance * pro * scaleFactor);

                    Point endPoint = relativeUserPoint(userCenterPoint, angle, (int) distance);

                    UserPoints userPoints = userPointsArrayList.get(a);
                    if ((Math.pow(endPoint.x, 2) + Math.pow(endPoint.y, 2)) < (Math.pow(j, 2) - (diff * 4))) {
                        //do nothing
                    } else {
                        do {
                            endPoint.x = endPoint.x - 10;
                            endPoint.y = endPoint.y - 10;
                        }
                        while ((Math.pow(endPoint.x, 2) + Math.pow(endPoint.y, 2)) < (Math.pow(j, 2) - (diff * 4)));
                    }

                    userPoints.setUserXCanvasPoint(endPoint.x);
                    userPoints.setUserYCanvasPoint(endPoint.y);

                    userPointsArrayList.set(a, userPoints);

                }

            }
            /*to avoid overlapping of markers we are moving points */
            for (int c = 0; c < userPointsArrayList.size()-1; c++) {
                int expAngle = 10;
                double expDistance = 30;
                Point canvasPoint = new Point((int) userPointsArrayList.get(c).getUserXCanvasPoint(), (int) userPointsArrayList.get(c).getUserYCanvasPoint());

                for (int d = 0; d < userPointsArrayList.size()-1; d++) {
                    Point comparePoint = new Point((int) userPointsArrayList.get(d).getUserXCanvasPoint(), (int) userPointsArrayList.get(d).getUserYCanvasPoint());
                    boolean xdiff = Math.abs(canvasPoint.x - comparePoint.x) <= 100;
                    boolean ydiff = Math.abs(canvasPoint.y - comparePoint.y) <= 100;
                    if (/*((canvasPoint.x == comparePoint.x) && (canvasPoint.y == comparePoint.y)) ||*/  xdiff || ydiff) {
                        if (c == d) break;
                        UserPoints userPoints = userPointsArrayList.get(d);

                        expAngle = expAngle + 10;

                        double angle = getAngle(userPointsArrayList.get(myPosition), userPoints) + expAngle;
                        double distance = calculateDistanceInMeter(userPointsArrayList.get(myPosition).userXLatPoint, userPointsArrayList.get(myPosition).userYLonPoint, userPoints.userXLatPoint, userPoints.userYLonPoint);
                        distance = (distance * pro * scaleFactor) + expDistance;

                        Point endPoint = relativeUserPoint(userCenterPoint, angle, (int) distance);

                        userPoints.setUserXCanvasPoint(endPoint.x);
                        userPoints.setUserYCanvasPoint(endPoint.y);
                        userPointsArrayList.set(d, userPoints);

                    }

                }


            }

            /*finaly we are drawing them*/
            for (int a = 0; a < userPointsArrayList.size(); a++) {

                if (a == myPosition) continue;
                else {

                    UserPoints userPoints = userPointsArrayList.get(a);
                    Drawable d = null;
                    Bitmap returnedBitmap = getMarkerBitmapFromView(userPoints);

                 /*   if (userPoints.getFriendshipStatus().equals("111")) {
                        d = getResources().getDrawable(R.drawable.ic_location_friend_pin);
                    } else {
                        d = getResources().getDrawable(R.drawable.ic_location_others_pin);
                    }
*/
                    if (returnedBitmap != null)
                        d = new BitmapDrawable(getResources(), returnedBitmap);
                    else
                        d = getResources().getDrawable(R.drawable.default_profile_pic);

                    d.setBounds((int) userPoints.getUserXCanvasPoint() - diff, (int) userPoints.getUserYCanvasPoint() - diff, (int) userPoints.getUserXCanvasPoint() + diff, (int) userPoints.getUserYCanvasPoint() + diff);
                    d.draw(canvas);
                    Log.d(LOG_TAG, "X::" + userPoints.getUserXCanvasPoint() + " Y::" + userPoints.getUserYCanvasPoint());
                }

            }


            stopAnimation();
        }


    }

    private Bitmap getMarkerBitmapFromView(UserPoints userPoints) {

        View customMarkerView = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.mapview_custom_marker, null);
        SimpleDraweeView markerImageView = (SimpleDraweeView) customMarkerView.findViewById(R.id.profile_image);
        SimpleDraweeView markerChannelView = (SimpleDraweeView) customMarkerView.findViewById(R.id.channel_profile_image);
        ImageView makerBackground = (ImageView) customMarkerView.findViewById(R.id.profile_image_bg);
        ImageView channelbg = (ImageView) customMarkerView.findViewById(R.id.profile_bg);
        RelativeLayout userLayout = (RelativeLayout) customMarkerView.findViewById(R.id.user_layout);
        RelativeLayout channelLayout = (RelativeLayout) customMarkerView.findViewById(R.id.channel_layout);
        /*user details*/
        Log.e("user_details " , userPoints.toString());
        if (userPoints.userDetails.getIs_user() == 1) {
            userLayout.setVisibility(VISIBLE);
            channelLayout.setVisibility(GONE);
            if (userPoints.getFriendshipStatus().equals("111")) {
                makerBackground.setBackgroundResource(R.drawable.ic_location_friend_pin);
            } else {
                makerBackground.setBackgroundResource(R.drawable.ic_location_others_pin);
            }
            if (!userPoints.getProfilePic().contains("user_profile_pic.png")) {
                Log.e("HERE" , "HERE");
                //markerImageView.setImageURI(Constants.ASSET_RESOURCE + userPoints.getProfilePic());
                markerImageView.setImageURI("https://dummyimage.com/420x320/ff7f7f/333333.png");
            } else {
                Uri uri = new Uri.Builder()
                        .scheme(UriUtil.LOCAL_RESOURCE_SCHEME)
                        .path(String.valueOf(R.drawable.default_profile_pic))
                        .build();
                markerImageView.setImageURI(uri);
            }
        }/*channel details*/ else {
            userLayout.setVisibility(GONE);
            channelLayout.setVisibility(VISIBLE);
            if (userPoints.userDetails.getChannelIsMember().equals("1") || userPoints.userDetails.getChannelIsAdmin().equals("1")) {
                channelbg.setBackgroundResource(R.drawable.ic_location_channel_member);
            } else {
                channelbg.setBackgroundResource(R.drawable.ic_location_channel_nonmember);
            }
            if (!userPoints.getUserDetails().getChannelProfilePicThumb().contains("user_profile_pic.png")) {
                String resource = Constants.SPARROW_ASSET_RESOURCE + userPoints.userDetails.getChannelProfilePicThumb();
//                markerChannelView.setImageURI(resource);
                ImageUtils.setResizedImageUri(markerChannelView, Uri.parse(resource));

            } else {
                Uri uri = new Uri.Builder()
                        .scheme(UriUtil.LOCAL_RESOURCE_SCHEME)
                        .path(String.valueOf(R.drawable.ic_channel_placeholder))
                        .build();
                markerChannelView.setImageURI(uri);
            }
        }

        customMarkerView.setDrawingCacheEnabled(true);
        customMarkerView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        customMarkerView.layout(0, 0, customMarkerView.getMeasuredWidth(), customMarkerView.getMeasuredHeight());
        customMarkerView.buildDrawingCache(true);
        Bitmap returnedBitmap = Bitmap.createBitmap(customMarkerView.getDrawingCache());
        customMarkerView.setDrawingCacheEnabled(false);
        return returnedBitmap;
    }



    @Override
    public boolean onTouchEvent(MotionEvent event) {

        Log.e(LOG_TAG, "UserTouch X::" + event.getX() + " Y::" + event.getY());


        for (int i = 0; i < userPointsArrayList.size() - 1; i++) {
            Point canvasPoint = new Point((int) userPointsArrayList.get(i).getUserXCanvasPoint(), (int) userPointsArrayList.get(i).getUserYCanvasPoint());
            Log.e(LOG_TAG, "Canvas X::" + canvasPoint.x + " Y::" + canvasPoint.y);

            if (Math.abs((canvasPoint.x - event.getX())) <= diff && Math.abs((canvasPoint.y - event.getY())) <= diff) {
                pinClickListener.onPinClicked(userPointsArrayList.get(i));
                Log.e(VRORadarView.class.getName(), "break");
                break;
            }
        }

        return super.onTouchEvent(event);
    }

    public double getAngle(UserPoints currentUser, UserPoints relativeUser) {
        double angle = Math.toDegrees(Math.atan2(relativeUser.userYLonPoint - currentUser.userYLonPoint, relativeUser.userXLatPoint - currentUser.userXLatPoint));

        if (angle < 0) {
            angle += 360;
        }

        return angle;
    }

    public float distanceBetweenPoints(UserPoints currentUser, UserPoints relativeUser) {
        float distance = (float) Math.sqrt(Math.pow(currentUser.userXLatPoint - relativeUser.userXLatPoint, 2) + Math.pow(currentUser.userYLonPoint - relativeUser.userYLonPoint, 2));

        return distance;
    }

    public Point relativeUserPoint(Point centerPoint, double angle, int radius) {

        Point finalPoint = new Point();

        finalPoint.x = (int) (centerPoint.x + radius * Math.cos(angle));

        finalPoint.y = (int) (centerPoint.y + radius * Math.sin(angle));

        return finalPoint;
    }

    public ArrayList<UserPoints> getUserPointsArrayList(){
        return userPointsArrayList;
    }

    public void setUserPointsArrayList(ArrayList<UserPoints> usersList) {
        userPointsArrayList.clear();
        this.userPointsArrayList = usersList;
        String rangeString = SharedPreference.getInstance().getStringPreference(PreferenceKeys.RANGE);
        rangeString.trim();
        if(rangeString == null || rangeString.length() == 0){
            rangeString = "1.2";
        }
        range = Double.valueOf(rangeString);

        Collections.sort(userPointsArrayList, new Comparator<UserPoints>() {

            public int compare(UserPoints s1, UserPoints s2) {
                return s1.getDistance() < s2.getDistance() ? -1 : s1.getDistance() > s2.getDistance() ? 1 : 0;
            }
        });
        Collections.reverse(userPointsArrayList);

        for (int k = 0; k < userPointsArrayList.size(); k++) {
            Log.d(LOG_TAG, "DIS::" + userPointsArrayList.get(k).getDistance());
        }
        startAnimation();
    }

    public double calculateDistanceInMeter(double userLat, double userLng,
                                           double venueLat, double venueLng) {

        double latDistance = Math.toRadians(userLat - venueLat);
        double lngDistance = Math.toRadians(userLng - venueLng);

        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
                + Math.cos(Math.toRadians(userLat)) * Math.cos(Math.toRadians(venueLat))
                * Math.sin(lngDistance / 2) * Math.sin(lngDistance / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

        return (Math.round(AVERAGE_RADIUS_OF_EARTH_METERS * c));
    }


    public static class UserPoints {
        private double userXLatPoint;
        private double userYLonPoint;
        private double userXCanvasPoint;
        private double userYCanvasPoint;

        private String userName;
        private double distance;
        private String location;
        private String profilePic;
        private String userId;
        private String friendshipStatus;
        private String ctc_user_name;

        private GetUserDetails userDetails;

        public UserPoints(double x, double y, GetUserDetails userDetails) {
            this.userXLatPoint = x;
            this.userYLonPoint = y;
            this.userDetails = userDetails;
        }


        public double getUserXCanvasPoint() {
            return userXCanvasPoint;
        }

        public void setUserXCanvasPoint(double userXCanvasPoint) {
            this.userXCanvasPoint = userXCanvasPoint;
        }

        public double getUserYCanvasPoint() {
            return userYCanvasPoint;
        }

        public void setUserYCanvasPoint(double userYCanvasPoint) {
            this.userYCanvasPoint = userYCanvasPoint;
        }

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public double getDistance() {
            return distance;
        }

        public void setDistance(double distance) {
            this.distance = distance;
        }

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        public String getProfilePic() {
            return profilePic;
        }

        public void setProfilePic(String profilePic) {
            this.profilePic = profilePic;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getFriendshipStatus() {
            return friendshipStatus;
        }

        public void setFriendshipStatus(String friendshipStatus) {
            this.friendshipStatus = friendshipStatus;
        }

        public String getCtc_user_name() {
            return ctc_user_name;
        }

        public void setCtc_user_name(String ctc_user_name) {
            this.ctc_user_name = ctc_user_name;
        }

        public GetUserDetails getUserDetails() {
            return userDetails;
        }

        public void setUserDetails(GetUserDetails userDetails) {
            this.userDetails = userDetails;
        }

        @Override
        public String toString() {
            return "UserPoints{" +
                    "userXLatPoint=" + userXLatPoint +
                    ", userYLonPoint=" + userYLonPoint +
                    ", userXCanvasPoint=" + userXCanvasPoint +
                    ", userYCanvasPoint=" + userYCanvasPoint +
                    ", userName='" + userName + '\'' +
                    ", distance=" + distance +
                    ", location='" + location + '\'' +
                    ", profilePic='" + profilePic + '\'' +
                    ", userId='" + userId + '\'' +
                    ", friendshipStatus='" + friendshipStatus + '\'' +
                    ", ctc_user_name='" + ctc_user_name + '\'' +
                    ", userDetails=" + userDetails +
                    '}';
        }
    }

}

Предполагается, что оно показывает пользовательское изображение, но ничего не показывает

Любая помощь приветствуется

Заранее спасибо

...