Custom View component is not showing up on the screenshot

大憨熊 提交于 2021-01-27 18:04:55

问题


I have a custom view named as HorizontalScaleView

public class HorizontalScaleView extends View {

private static float THICK_STROKE_WIDTH = 16.0f;
private static float THIN_STROKE_WIDTH = 8.0f;
private static float THINNER_STROKE_WIDTH = 4.0f;

private int mColorStartGradient;
private int mColorEndGradient;
private int mColorOptimum;
private int mColorLineGradientStart;
private int mColorLineGradientEnd;
private int mColorDarkerGrey;

private int mMaxOptimumValue = 1000;

private Paint mLinePaint;
private Paint mTargetPaint;

private int mWidth;
private int mHeight;

private int markerValue = 0;
private int targetValue = 700;
private int averageValue = -1;

private Drawable mMarkerDrawable;
private Drawable mTargetDrawable;

private Rect markerRect = new Rect();
private Rect targetRect = new Rect();

public HorizontalScaleView(Context context) {
    super(context);
    mColorStartGradient = ContextCompat.getColor(context, R.color.colorBackGradientStart);
    mColorEndGradient = ContextCompat.getColor(context, R.color.score_maintain);
    mColorOptimum = ContextCompat.getColor(context, R.color.score_maintain);
    mColorDarkerGrey = ContextCompat.getColor(context, R.color.textColorDarkGrey);
    init(context);
}

public HorizontalScaleView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    TypedArray attributes = context.getTheme().obtainStyledAttributes(
            attrs,
            R.styleable.HorizontalScaleView,
            0, 0);
    try {
        mColorStartGradient = attributes.getColor(R.styleable.HorizontalScaleView_color_back_gradient_start,
                ContextCompat.getColor(context, R.color.colorBackGradientStart));
        mColorEndGradient = attributes.getColor(R.styleable.HorizontalScaleView_color_back_gradient_end,
                ContextCompat.getColor(context, R.color.score_maintain));
        mColorOptimum = attributes.getColor(R.styleable.HorizontalScaleView_color_optimum,
                ContextCompat.getColor(context, R.color.score_maintain));
        mColorLineGradientStart = attributes.getColor(R.styleable.HorizontalScaleView_color_gradient_start,
                ContextCompat.getColor(context, R.color.line_gradient_start));
        mColorLineGradientEnd = attributes.getColor(R.styleable.HorizontalScaleView_color_gradient_end,
                ContextCompat.getColor(context, R.color.line_gradient_end));
        mColorDarkerGrey = attributes.getColor(R.styleable.HorizontalScaleView_color_marker,
                ContextCompat.getColor(context, R.color.textColorDarkGrey));
        mMaxOptimumValue = attributes.getInteger(R.styleable.HorizontalScaleView_max_optimum_value,
                1000);
        targetValue = attributes.getInteger(R.styleable.HorizontalScaleView_target_value,
                0);
        averageValue = attributes.getInteger(R.styleable.HorizontalScaleView_average_value,
                -1);
    } finally {
        attributes.recycle();
    }
    init(context);
}

private void init(Context context) {
    mLinePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mLinePaint.setStrokeWidth(THINNER_STROKE_WIDTH);

    mTargetPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mTargetPaint.setStrokeWidth(THINNER_STROKE_WIDTH);
    mTargetPaint.setColor(ContextCompat.getColor(context, android.R.color.black));

    mMarkerDrawable = context.getDrawable(R.drawable.ic_marker);
    mTargetDrawable = context.getDrawable(R.drawable.ic_arrow_drop_up_black);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    mWidth = MeasureSpec.getSize(widthMeasureSpec);
    mHeight = MeasureSpec.getSize(heightMeasureSpec);
    setMeasuredDimension(mWidth, mHeight);
}

@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
    canvas.save();
    mWidth = getWidth();
    int gap = (mHeight * 10) / 100;
    int sidePadding = 2 * gap;
    mWidth -= 2 * sidePadding;
    mLinePaint.setTextSize((mHeight * 15) / 100);
    mTargetPaint.setTextSize((mHeight * 15) / 100);
    float optimumStopX = mWidth + sidePadding;
    THIN_STROKE_WIDTH = (mHeight * 25) / 1000;
    THINNER_STROKE_WIDTH = (mHeight * 15) / 1000;


    Shader shader = new LinearGradient(sidePadding, mHeight / 2, optimumStopX, mHeight / 2,
            mColorLineGradientStart, mColorLineGradientEnd, Shader.TileMode.CLAMP);
    mLinePaint.setShader(shader);
    mLinePaint.setStrokeWidth(mHeight * 4 / 100);
    canvas.drawLine(sidePadding, mHeight * 32 / 100, optimumStopX, mHeight * 32 / 100, mLinePaint);
    mLinePaint.setShader(null);

    //Drawing background Gradient
    int gradientHeight = (mHeight * 16) / 100;
    shader = new LinearGradient(0, gradientHeight, mWidth + sidePadding + THIN_STROKE_WIDTH, gradientHeight,
            mColorStartGradient, mColorEndGradient, Shader.TileMode.CLAMP);
    mLinePaint.setShader(shader);
    mLinePaint.setStrokeWidth(mHeight * 32 / 100);
    mLinePaint.setAlpha(30);
    canvas.drawLine(0, gradientHeight, mWidth + sidePadding + THIN_STROKE_WIDTH, gradientHeight, mLinePaint);
    mLinePaint.setShader(null);

    int borderLineHeight = (mHeight * 5) / 100;
    mLinePaint.setAlpha(0);
    mLinePaint.setStrokeWidth(THIN_STROKE_WIDTH);
    mLinePaint.setColor(mColorLineGradientEnd);
    canvas.drawLine(optimumStopX, (mHeight * 32 / 100) - borderLineHeight, optimumStopX, (mHeight * 32 / 100) + borderLineHeight, mLinePaint);
    mLinePaint.setColor(mColorLineGradientStart);
    canvas.drawLine(sidePadding, (mHeight * 32 / 100) - borderLineHeight, sidePadding, (mHeight * 32 / 100) + borderLineHeight, mLinePaint);


    // Drawing Grade i.e  0  '  100  '  200  '  300 ....... 1000
    int gradeWidth = (int) ((optimumStopX - sidePadding) / 10);
    int gradePositionX = sidePadding;
    int gradePositionY = (mHeight * 44) / 100;
    int gradeHeight = (mHeight * 3) / 100;
    int gradeTextHeight = (mHeight * 58) / 100;

    mLinePaint.setStrokeWidth(THIN_STROKE_WIDTH);
    mLinePaint.setTextSize((mHeight * 10) / 100);
    canvas.drawText("0", gradePositionX, gradeTextHeight, mLinePaint);
    for (int index = 1; index < 10; index++) {
        gradePositionX += gradeWidth;
        if (index % 2 == 0) {
            mLinePaint.setStrokeWidth(THIN_STROKE_WIDTH);
            canvas.drawLine(gradePositionX, gradePositionY - gradeHeight, gradePositionX,
                    gradePositionY + gradeHeight, mLinePaint);
            if ((index * 100) != targetValue) {
                mLinePaint.setStrokeWidth(THIN_STROKE_WIDTH);
                canvas.drawText(String.valueOf(index * 100), gradePositionX - ((mHeight * 8) / 100), gradeTextHeight, mLinePaint);
            }
        } else {
            mLinePaint.setStrokeWidth(THINNER_STROKE_WIDTH);
            canvas.drawLine(gradePositionX, gradePositionY - gradeHeight, gradePositionX,
                    gradePositionY + gradeHeight, mLinePaint);

        }
    }
    canvas.drawText("1000", optimumStopX - ((mHeight * 22) / 100), gradeTextHeight, mLinePaint);

    //Drawing Current Position
    int markerPositionX = (int) (((optimumStopX - sidePadding) / mMaxOptimumValue) * markerValue);
    markerPositionX += sidePadding;
    int markerPositionY = mHeight * 34 / 100;
    int markerWidth = (mHeight * 5 / 100);
    int markerHeight = (mHeight * 65 / 1000);
    mMarkerDrawable.setTint(mColorDarkerGrey);
    markerRect.set(markerPositionX - 2 * markerWidth, markerPositionY - (5 * markerHeight),
            markerPositionX + 2 * markerWidth, markerPositionY - markerHeight);
    mMarkerDrawable.setBounds(markerRect);
    mMarkerDrawable.draw(canvas);
    canvas.restore();

    //Drawing Target Position
    if (targetValue <= 0) {
        return;
    }
    mTargetPaint.setColor(mColorOptimum);
    mTargetPaint.setStrokeWidth(THIN_STROKE_WIDTH);
    mTargetPaint.setTextSize(mHeight * 18 / 100);
    int targetPositionX = (int) (((optimumStopX - sidePadding) / mMaxOptimumValue) * targetValue);
    int targetPositionY = mHeight * 58 / 100;
    targetPositionX += sidePadding;
    int targetWidth = (mHeight * 5 / 100);
    int targetHeight = (mHeight * 4 / 100);
    targetRect.set(targetPositionX - 2 * targetWidth, targetPositionY - targetHeight,
            targetPositionX + 2 * targetWidth, targetPositionY + (4 * targetHeight));
    mTargetDrawable.setTint(mColorOptimum);
    mTargetDrawable.setBounds(targetRect);
    mTargetDrawable.draw(canvas);
    canvas.drawText(String.valueOf(targetValue), targetPositionX - (mHeight * 15 / 100), (mHeight * 82) / 100, mTargetPaint);
    mTargetPaint.setTextSize(mHeight * 10 / 100);
    canvas.drawText("Target", targetPositionX - (mHeight * 14 / 100), (mHeight * 95) / 100, mTargetPaint);

    //Drawing Average Value
    if (averageValue <= 0) {
        return;
    }
    mTargetPaint.setColor(mColorDarkerGrey);
    mTargetPaint.setStrokeWidth(THIN_STROKE_WIDTH);
    mTargetPaint.setTextSize(mHeight * 18 / 100);
    int averageValuePosition = (int) (((optimumStopX - sidePadding) / mMaxOptimumValue) * averageValue);
    averageValuePosition += sidePadding;
    targetRect.set(averageValuePosition - 2 * targetWidth, targetPositionY - targetHeight,
            averageValuePosition + 2 * targetWidth, targetPositionY + (4 * targetHeight));
    mTargetDrawable.setBounds(targetRect);
    mTargetDrawable.draw(canvas);
    canvas.drawText(String.valueOf(averageValue), averageValuePosition - 65, (mHeight * 82) / 100, mTargetPaint);
    mTargetPaint.setTextSize(mHeight * 10 / 100);
    canvas.drawText("Average", averageValuePosition - 70, (mHeight * 95) / 100, mTargetPaint);
    mTargetPaint.setColorFilter(null);

}

public void setMarkerValue(int markerValue) {
    this.markerValue = markerValue;
    invalidate();
    requestLayout();
}

public void setTargetValue(int targetValue) {
    this.targetValue = targetValue;
    invalidate();
    requestLayout();
}
}

I used it in one of my layout files:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical">

    <TextView
        android:id="@+id/score_card_desc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="12dp"
        android:layout_marginRight="16dp"
        android:text="@string/dashboard_household_score_card_desc"
        android:textColor="@color/textColorDarkGrey"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/score_card_score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/score_card_desc"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="-8dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="-8dp"
        android:fontFamily="sans-serif-light"
        android:textColor="@color/textColorDarkGrey"
        android:textSize="100sp"
        tools:text="655" />


    <com.kroger.mobile.components.HorizontalScaleView
        android:id="@+id/score_card_graph"
        style="@style/HorizontalScaleView"
        android:layout_width="400dp"
        android:layout_height="120dp"
        android:layout_below="@+id/score_card_score"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        app:max_optimum_value="1000"
        app:target_value="@integer/dashboard_target" />

</RelativeLayout>
</layout>

Now I want to take screenshot of this layout programmatically without displaying it on the screen and then and share it

I use these functions to generate, store and share screenshot respectively

 private Bitmap generateScreenShot(Household household) {
    LayoutDashboardScreenShotBinding shareBinding =
            DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.layout_dashboard_screen_shot, null, false);
    shareBinding.scoreCardScore.setText(String.valueOf(household.overallScore));
    shareBinding.scoreCardGraph.setMarkerValue(household.overallScore);
    shareBinding.scoreCardGraph.setTargetValue(0);

    View shareView = shareBinding.getRoot();
    shareView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
    shareView.layout(0, 0, shareView.getMeasuredWidth(), shareView.getMeasuredHeight());

    Bitmap bitmap = Bitmap.createBitmap(shareView.getWidth(), shareView.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    shareView.draw(canvas);
    return bitmap;
}

public File storeScreenShot(Bitmap bm, String fileName){
    String dirPath = Environment.getExternalStorageDirectory().getAbsolutePath() + DIRECTORY_PATH;
    File dir = new File(dirPath);
    if(dir.exists() || dir.mkdirs()) {
        File file = new File(dirPath, fileName);
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return null;
}

private void shareImage(File file){
    Context context = getContext();
    if(context == null){
        return;
    }
    Uri uri = FileProvider.getUriForFile(context,
            context.getApplicationContext().getPackageName() + ".provider", file);
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_SEND);
    intent.setType("image/*");
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "");
    intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
    intent.putExtra(Intent.EXTRA_STREAM, uri);
    try {
        startActivity(Intent.createChooser(intent, "Share Screenshot"));
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, "No App Available", Toast.LENGTH_SHORT).show();
    }
}

What I expect to capture in that screenshot is:

But what I am getting is:

The custom view that I have in this layout is not showing up on the screenshot.


回答1:


Maybe HorizontalScaleView.setMeasuredDimensions() is getting called with 0,0 because you did not handle the case of MeasureSpecs like UNSPECIFIED, which would have a getSize() of 0 :)



来源:https://stackoverflow.com/questions/53181261/custom-view-component-is-not-showing-up-on-the-screenshot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!