Reputation: 634
Suppose I put some points as (x1,y1) = (133,123), (x2,y2) = (149,136), (x3,y3) = (182,136) and so on which makes a shape something like this:
Now I want to change the position of these points as per the screen resolution such that the shape gets resized and gets centered and also such that the shape doesn't get damaged. Please help me.
Upvotes: 1
Views: 1016
Reputation: 12717
you can use onMeasure method to get measure then you can start painting with that position. I dont know below code is working truly, maybe it need to be optimized.
protected void onDraw(Canvas canvas) {
int height = getMeasuredHeight();
int width = getMeasuredWidth();
// Find the center
px = width / 2;
py = height / 2;
canvas.drawColor(BACKGROUND);
canvas.drawBitmap(mBitmap, 0, 0, null);
canvas.drawPath(mPath, mPaint);
// TODO remove if you dont want points to be drawn
for (Point point : mPoints) {
canvas.drawPoint(point.x + px, point.y + py, mPaint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measuredHeight = measureHeight(heightMeasureSpec);
int measuredWidth = measureWidth(widthMeasureSpec);
setMeasuredDimension(measuredHeight, measuredWidth);
}
private int measureHeight(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
// Default size if no limits are specified.
int result = 500;
if (specMode == MeasureSpec.AT_MOST) {
// Calculate the ideal size of your
// control within this maximum size.
// If your control fills the available
// space return the outer bound.
result = specSize;
} else if (specMode == MeasureSpec.EXACTLY) {
// If your control can fit within these bounds return that value.
result = specSize;
}
return result;
}
private int measureWidth(int measureSpec) {
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
// Default size if no limits are specified.
int result = 500;
if (specMode == MeasureSpec.AT_MOST) {
// Calculate the ideal size of your control
// within this maximum size.
// If your control fills the available space
// return the outer bound.
result = specSize;
} else if (specMode == MeasureSpec.EXACTLY) {
// If your control can fit within these bounds return that value.
result = specSize;
}
return result;
}
Upvotes: 1
Reputation: 37915
You can grab the scale factor from the DisplayMetrics
as shown in the Android - Supporting Multiple Screens documentation:
final float scale = getResources().getDisplayMetrics().density;
Multiply all you x and y coordinates with scale
and your points are screen density independent.
To fit the image on the screen (or View
probably), you can grab the width and height of your View. Check the width and height of your image and calculate the maximum scale factor.
Combine (multiply) both scale factors and your image should fit your View.
Upvotes: 2