can any one help me to create balow image cutomize seek bar
i have already go throught
SeekBar with custom thumb and segmented text
and SeekBar Thumb position issue
but i am not success to create my custome seekbar pls help me
Use Library From This Link: This link and put into your project,
Now Create A Seekbar Like This Class:
package com.tokaracamara.android.verticalslidevar;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class DemoSeek extends AbsVerticalSeekBar {
public interface OnSeekBarChangeListener {
void onProgressChanged(DemoSeek seekBar, int progress, boolean fromUser);
void onStartTrackingTouch(DemoSeek seekBar);
void onStopTrackingTouch(DemoSeek seekBar);
}
private OnSeekBarChangeListener mOnSeekBarChangeListener;
private Drawable progressDrawable;
private Rect barBounds, labelTextRect;
private Bitmap labelBackground;
private Point labelPos;
private Paint labelTextPaint, labelBackgroundPaint;
int viewWidth, barHeight, labelOffset;
// private int thumbX;
float progressPosX;
private String expression;
public DemoSeek(Context context) {
super(context);
// Log.i("Seekbar", "DemoSeek");
progressDrawable = getProgressDrawable();
// labelBackground = BitmapFactory.decodeResource(getResources(),
// R.drawable.thumb_marker);
labelBackground = drawableToBitmap(mThumb);
labelTextPaint = new Paint();
labelTextPaint.setColor(Color.WHITE);
labelTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
labelTextPaint.setAntiAlias(true);
labelTextPaint.setDither(true);
labelTextPaint.setTextSize(13f);
labelBackgroundPaint = new Paint();
barBounds = new Rect();
labelTextRect = new Rect();
labelPos = new Point();
}
public Bitmap drawableToBitmap(Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
#Override
void onProgressRefresh(float scale, boolean fromUser) {
super.onProgressRefresh(scale, fromUser);
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onProgressChanged(this, getProgress(),
fromUser);
}
}
public DemoSeek(Context context, AttributeSet attrs) {
super(context, attrs);
progressDrawable = getProgressDrawable();
labelBackground = BitmapFactory.decodeResource(getResources(),
R.drawable.thumb_with_arrow);
labelTextPaint = new Paint();
labelTextPaint.setColor(Color.WHITE);
labelTextPaint.setTypeface(Typeface.DEFAULT_BOLD);
labelTextPaint.setAntiAlias(true);
labelTextPaint.setDither(true);
labelTextPaint.setTextSize(15f);
labelBackgroundPaint = new Paint();
barBounds = new Rect();
labelTextRect = new Rect();
labelPos = new Point();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Log.i("Seekbar", "onMeasure");
if (labelBackground != null) {
viewWidth = getMeasuredWidth();
barHeight = getMeasuredHeight() - getPaddingTop()
- getPaddingBottom();
setMeasuredDimension(viewWidth + labelBackground.getWidth(),
barHeight + labelBackground.getHeight() / 2);
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
if (labelBackground != null) {
barBounds.left = getPaddingLeft();
barBounds.top = (int) (labelBackground.getHeight() / 2f);
barBounds.right = barBounds.left + viewWidth - getPaddingRight()
- getPaddingLeft();
barBounds.bottom = barBounds.top + barHeight - getPaddingBottom()
- getPaddingTop();
progressPosX = barBounds.top
+ ((float) this.getProgress() / (float) this.getMax())
* barBounds.height() + getTopPaddingOffset();
labelPos.y = getBottom() - (int) progressPosX - labelOffset
+ (int) (getProgress() * 0.1f);
labelPos.x = getPaddingLeft();
progressDrawable = getProgressDrawable();
progressDrawable.setBounds(barBounds.left, barBounds.top,
barBounds.right, getBottom());
progressDrawable.draw(canvas);
String pro = getProgress() * multiplier + "";
if (expression != null) {
pro = pro.concat(expression);
}
labelTextPaint.getTextBounds(pro, 0, pro.length(), labelTextRect);
canvas.drawBitmap(labelBackground, labelPos.x, labelPos.y,
labelBackgroundPaint);
canvas.drawText(pro, labelPos.x + labelBackground.getWidth() / 2
- labelTextRect.width() / 2 + 15, labelPos.y
+ labelBackground.getHeight() / 2 + labelTextRect.height()
/ 2 - 5, labelTextPaint);
}
canvas.restore();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
invalidate();
return super.onTouchEvent(event);
}
public void setOnSeekBarChangeListener(
com.tokaracamara.android.verticalslidevar.DemoSeek.OnSeekBarChangeListener onSeekBarChangeListener) {
mOnSeekBarChangeListener = (OnSeekBarChangeListener) onSeekBarChangeListener;
}
#Override
void onStartTrackingTouch() {
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStartTrackingTouch(this);
}
}
#Override
void onStopTrackingTouch() {
if (mOnSeekBarChangeListener != null) {
mOnSeekBarChangeListener.onStopTrackingTouch(this);
}
}
private int multiplier = 1;
public void setMultiplier(int multiplier) {
this.multiplier = multiplier;
}
public int getMultiplier() {
return multiplier;
}
public void setExpression(String expression) {
this.expression = expression.trim();
}
public String getExpression() {
return expression;
}
}
Create Xml Like This:
<com.tokaracamara.android.verticalslidevar.DemoSeek
android:id="#+id/v_four_university"
android:layout_width="#dimen/vs_width"
android:layout_height="match_parent"
android:clickable="false"
android:focusable="false"
android:longClickable="false"
android:progress="50"
android:progressDrawable="#drawable/progress_vertical"
android:saveEnabled="false"
android:thumb="#drawable/your thumb" />
Related
I created a cornerRadius card view and my codes work well in activity but the problem now is that the cardview does not show the rounded edges and elevation in fragment but it shows in the design codes and in activity. my codes are shown blow:
raounded_corners.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:focusable="true"
android:clickable="true"
android:background="#color/white"
android:layout_height="match_parent">
<com.google.android.material.card.MaterialCardView
android:id="#+id/text_bg"
android:layout_width="110dp"
android:layout_height="110dp"
app:cardBackgroundColor="#color/green_500"
app:cardCornerRadius="50dp"
app:cardElevation="5dp"
android:layout_gravity="center"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<ImageView
android:id="#+id/image_session"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:src="#drawable/photo_male_7" />
</com.google.android.material.card.MaterialCardView>
</RelativeLayout>
In Fragment
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.raounded_corners,container,false);
return v;
}
raounded_corners.xml layout cornerRadius showing in activity but not showing in fragment
How to fix this.
In Activity
in fragment
If you are trying to make the imageview circular, I propose this approach.Create the custom view and set it in your xml. It works perfectly. If this helps you, an upvote will be appreciated.
Create a custom Circular view like shown below. CircleImageView.java
package com.fishpott.fishpott5.Views;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.annotation.ColorInt;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.widget.ImageView;
import com.fishpott.fishpott5.R;
public class CircleImageView extends AppCompatImageView {
private static final ImageView.ScaleType SCALE_TYPE = ImageView.ScaleType.CENTER_CROP;
private static final Bitmap.Config BITMAP_CONFIG = Bitmap.Config.ARGB_8888;
private static final int COLORDRAWABLE_DIMENSION = 2;
private static final int DEFAULT_BORDER_WIDTH = 0;
private static final int DEFAULT_BORDER_COLOR = Color.BLACK;
private static final int DEFAULT_FILL_COLOR = Color.TRANSPARENT;
private static final boolean DEFAULT_BORDER_OVERLAY = false;
private final RectF mDrawableRect = new RectF();
private final RectF mBorderRect = new RectF();
private final Matrix mShaderMatrix = new Matrix();
private final Paint mBitmapPaint = new Paint();
private final Paint mBorderPaint = new Paint();
private final Paint mFillPaint = new Paint();
private int mBorderColor = DEFAULT_BORDER_COLOR;
private int mBorderWidth = DEFAULT_BORDER_WIDTH;
private int mFillColor = DEFAULT_FILL_COLOR;
private Bitmap mBitmap;
private BitmapShader mBitmapShader;
private int mBitmapWidth;
private int mBitmapHeight;
private float mDrawableRadius;
private float mBorderRadius;
private ColorFilter mColorFilter;
private boolean mReady;
private boolean mSetupPending;
private boolean mBorderOverlay;
private boolean mDisableCircularTransformation;
public CircleImageView(Context context) {
super(context);
init();
}
public CircleImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CircleImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleImageView, defStyle, 0);
mBorderWidth = a.getDimensionPixelSize(R.styleable.CircleImageView_civ_border_width, DEFAULT_BORDER_WIDTH);
mBorderColor = a.getColor(R.styleable.CircleImageView_civ_border_color, DEFAULT_BORDER_COLOR);
mBorderOverlay = a.getBoolean(R.styleable.CircleImageView_civ_border_overlay, DEFAULT_BORDER_OVERLAY);
mFillColor = a.getColor(R.styleable.CircleImageView_civ_fill_color, DEFAULT_FILL_COLOR);
a.recycle();
init();
}
private void init() {
super.setScaleType(SCALE_TYPE);
mReady = true;
if (mSetupPending) {
setup();
mSetupPending = false;
}
}
#Override
public ImageView.ScaleType getScaleType() {
return SCALE_TYPE;
}
#Override
public void setScaleType(ImageView.ScaleType scaleType) {
if (scaleType != SCALE_TYPE) {
throw new IllegalArgumentException(String.format("ScaleType %s not supported.", scaleType));
}
}
#Override
public void setAdjustViewBounds(boolean adjustViewBounds) {
if (adjustViewBounds) {
throw new IllegalArgumentException("adjustViewBounds not supported.");
}
}
#Override
protected void onDraw(Canvas canvas) {
if (mDisableCircularTransformation) {
super.onDraw(canvas);
return;
}
if (mBitmap == null) {
return;
}
if (mFillColor != Color.TRANSPARENT) {
canvas.drawCircle(mDrawableRect.centerX(), mDrawableRect.centerY(), mDrawableRadius, mFillPaint);
}
canvas.drawCircle(mDrawableRect.centerX(), mDrawableRect.centerY(), mDrawableRadius, mBitmapPaint);
if (mBorderWidth > 0) {
canvas.drawCircle(mBorderRect.centerX(), mBorderRect.centerY(), mBorderRadius, mBorderPaint);
}
}
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
setup();
}
#Override
public void setPadding(int left, int top, int right, int bottom) {
super.setPadding(left, top, right, bottom);
setup();
}
#Override
public void setPaddingRelative(int start, int top, int end, int bottom) {
super.setPaddingRelative(start, top, end, bottom);
setup();
}
public int getBorderColor() {
return mBorderColor;
}
public void setBorderColor(#ColorInt int borderColor) {
if (borderColor == mBorderColor) {
return;
}
mBorderColor = borderColor;
mBorderPaint.setColor(mBorderColor);
invalidate();
}
/**
* #deprecated Use {#link #setBorderColor(int)} instead
*/
#Deprecated
public void setBorderColorResource(#ColorRes int borderColorRes) {
setBorderColor(getContext().getResources().getColor(borderColorRes));
}
/**
* Return the color drawn behind the circle-shaped drawable.
*
* #return The color drawn behind the drawable
*
* #deprecated Fill color support is going to be removed in the future
*/
#Deprecated
public int getFillColor() {
return mFillColor;
}
/**
* Set a color to be drawn behind the circle-shaped drawable. Note that
* this has no effect if the drawable is opaque or no drawable is set.
*
* #param fillColor The color to be drawn behind the drawable
*
* #deprecated Fill color support is going to be removed in the future
*/
#Deprecated
public void setFillColor(#ColorInt int fillColor) {
if (fillColor == mFillColor) {
return;
}
mFillColor = fillColor;
mFillPaint.setColor(fillColor);
invalidate();
}
/**
* Set a color to be drawn behind the circle-shaped drawable. Note that
* this has no effect if the drawable is opaque or no drawable is set.
*
* #param fillColorRes The color resource to be resolved to a color and
* drawn behind the drawable
*
* #deprecated Fill color support is going to be removed in the future
*/
#Deprecated
public void setFillColorResource(#ColorRes int fillColorRes) {
setFillColor(getContext().getResources().getColor(fillColorRes));
}
public int getBorderWidth() {
return mBorderWidth;
}
public void setBorderWidth(int borderWidth) {
if (borderWidth == mBorderWidth) {
return;
}
mBorderWidth = borderWidth;
setup();
}
public boolean isBorderOverlay() {
return mBorderOverlay;
}
public void setBorderOverlay(boolean borderOverlay) {
if (borderOverlay == mBorderOverlay) {
return;
}
mBorderOverlay = borderOverlay;
setup();
}
public boolean isDisableCircularTransformation() {
return mDisableCircularTransformation;
}
public void setDisableCircularTransformation(boolean disableCircularTransformation) {
if (mDisableCircularTransformation == disableCircularTransformation) {
return;
}
mDisableCircularTransformation = disableCircularTransformation;
initializeBitmap();
}
#Override
public void setImageBitmap(Bitmap bm) {
super.setImageBitmap(bm);
initializeBitmap();
}
#Override
public void setImageDrawable(Drawable drawable) {
super.setImageDrawable(drawable);
initializeBitmap();
}
#Override
public void setImageResource(#DrawableRes int resId) {
super.setImageResource(resId);
initializeBitmap();
}
#Override
public void setImageURI(Uri uri) {
super.setImageURI(uri);
initializeBitmap();
}
#Override
public void setColorFilter(ColorFilter cf) {
if (cf == mColorFilter) {
return;
}
mColorFilter = cf;
applyColorFilter();
invalidate();
}
#Override
public ColorFilter getColorFilter() {
return mColorFilter;
}
private void applyColorFilter() {
if (mBitmapPaint != null) {
mBitmapPaint.setColorFilter(mColorFilter);
}
}
private Bitmap getBitmapFromDrawable(Drawable drawable) {
if (drawable == null) {
return null;
}
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
try {
Bitmap bitmap;
if (drawable instanceof ColorDrawable) {
bitmap = Bitmap.createBitmap(COLORDRAWABLE_DIMENSION, COLORDRAWABLE_DIMENSION, BITMAP_CONFIG);
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), BITMAP_CONFIG);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private void initializeBitmap() {
if (mDisableCircularTransformation) {
mBitmap = null;
} else {
mBitmap = getBitmapFromDrawable(getDrawable());
}
setup();
}
private void setup() {
if (!mReady) {
mSetupPending = true;
return;
}
if (getWidth() == 0 && getHeight() == 0) {
return;
}
if (mBitmap == null) {
invalidate();
return;
}
mBitmapShader = new BitmapShader(mBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mBitmapPaint.setAntiAlias(true);
mBitmapPaint.setShader(mBitmapShader);
mBorderPaint.setStyle(Paint.Style.STROKE);
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderWidth);
mFillPaint.setStyle(Paint.Style.FILL);
mFillPaint.setAntiAlias(true);
mFillPaint.setColor(mFillColor);
mBitmapHeight = mBitmap.getHeight();
mBitmapWidth = mBitmap.getWidth();
mBorderRect.set(calculateBounds());
mBorderRadius = Math.min((mBorderRect.height() - mBorderWidth) / 2.0f, (mBorderRect.width() - mBorderWidth) / 2.0f);
mDrawableRect.set(mBorderRect);
if (!mBorderOverlay && mBorderWidth > 0) {
mDrawableRect.inset(mBorderWidth - 1.0f, mBorderWidth - 1.0f);
}
mDrawableRadius = Math.min(mDrawableRect.height() / 2.0f, mDrawableRect.width() / 2.0f);
applyColorFilter();
updateShaderMatrix();
invalidate();
}
private RectF calculateBounds() {
int availableWidth = getWidth() - getPaddingLeft() - getPaddingRight();
int availableHeight = getHeight() - getPaddingTop() - getPaddingBottom();
int sideLength = Math.min(availableWidth, availableHeight);
float left = getPaddingLeft() + (availableWidth - sideLength) / 2f;
float top = getPaddingTop() + (availableHeight - sideLength) / 2f;
return new RectF(left, top, left + sideLength, top + sideLength);
}
private void updateShaderMatrix() {
float scale;
float dx = 0;
float dy = 0;
mShaderMatrix.set(null);
if (mBitmapWidth * mDrawableRect.height() > mDrawableRect.width() * mBitmapHeight) {
scale = mDrawableRect.height() / (float) mBitmapHeight;
dx = (mDrawableRect.width() - mBitmapWidth * scale) * 0.5f;
} else {
scale = mDrawableRect.width() / (float) mBitmapWidth;
dy = (mDrawableRect.height() - mBitmapHeight * scale) * 0.5f;
}
mShaderMatrix.setScale(scale, scale);
mShaderMatrix.postTranslate((int) (dx + 0.5f) + mDrawableRect.left, (int) (dy + 0.5f) + mDrawableRect.top);
mBitmapShader.setLocalMatrix(mShaderMatrix);
}
}
Set the view in your xml
<com.fishpott.fishpott5.Views.CircleImageView
android:id="#+id/activity_setprofilepicture_profilepicture_imageview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:contentDescription="#string/none"
android:src="#drawable/setprofilepicture_activity_imageholder_default_image"
app:civ_border_color="#android:color/transparent"
app:civ_border_width="0dp" />
The reason you see "Views" in my xml call of the CircleImageView is because my CircleImageView.java is in "Views" folder/package.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
When I run my android app, it crashes and says that Android app has stopped. It also gives this error message:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.esimerkki.doodl2.DoodleView com.esimerkki.doodl2.FirstFragment.getDoodleView()' on a null object reference
What is wrong with this? Is the reference really null? How could I make this work? I thought these original settings in doodleView have start values?
Here is the code of doodleView class:
package com.esimerkki.doodl2;
import android.content.Context;
import android.view.View;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.provider.MediaStore;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.widget.Toast;
import androidx.print.PrintHelper;
import java.util.HashMap;
import java.util.Map;
public class DoodleView extends View {
public DoodleView(Context context, Paint paintScreen, Paint paintLine) {
super( context );
this.paintScreen = paintScreen;
this.paintLine = paintLine;
}
private static final float TOUCH_TOLERANCE = 10;
private Bitmap bitmap; // drawing area
private Canvas bitmapCanvas; //
private final Paint paintScreen; //
private final Paint paintLine; //
private final Map<Integer, Path> pathMap = new HashMap<>();
private final Map<Integer, Point> previousPointMap = new HashMap<>();
public DoodleView(Context context, AttributeSet attrs) {
super(context, attrs); // kutsutaan yliluokanalustajaa
paintScreen = new Paint(); // bittikartan näyttämiseen ruudulla
paintLine = new Paint();
paintLine.setAntiAlias(true);
paintLine.setColor(Color.BLACK);
paintLine.setStyle(Paint.Style.STROKE);
paintLine.setStrokeWidth(5);
paintLine.setStrokeCap(Paint.Cap.ROUND);
#Override
public void onSizeChanged(int w, int h, int OldW, int oldH) {
bitmap = Bitmap.createBitmap(getWidth(), getHeight(),
Bitmap.Config.ARGB_8888);
bitmapCanvas = new Canvas(bitmap);
bitmap.eraseColor(Color.WHITE);
}
public void clear() {
pathMap.clear();
previousPointMap.clear();
bitmap.eraseColor(Color.WHITE);
invalidate();
}
public void setDrawingColor(int color) {
paintLine.setColor(color);
}
public int getDrawingColor() {
return paintLine.getColor();
}
public void setLineWidth(int width) {
paintLine.setStrokeWidth(width);
}
public int getLineWidth() {
return (int) paintLine.getStrokeWidth();
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, paintScreen);
for (Integer key : pathMap.keySet())
canvas.drawPath(pathMap.get(key), paintLine); // piirretään viiva
}
#Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getActionMasked(); // tapahtumatyyppi
int actionIndex = event.getActionIndex(); // osoitin
if (action == MotionEvent.ACTION_DOWN ||
action == MotionEvent.ACTION_POINTER_DOWN) {
touchStarted(event.getX(actionIndex), event.getY(actionIndex),
event.getPointerId(actionIndex));
}
else if (action == MotionEvent.ACTION_UP ||
action == MotionEvent.ACTION_POINTER_UP) {
touchEnded(event.getPointerId(actionIndex));
}
else {
touchMoved(event);
}
invalidate();
return true;
}
private void touchStarted(float x, float y, int lineID) {
Path path; // tallennetaan tietyn id:n polku
Point point; // tallennetaan polun viimeinen piste
if (pathMap.containsKey(lineID)) {
path = pathMap.get(lineID);
path.reset();
point = previousPointMap.get(lineID);
}
else {
path = new Path();
pathMap.put(lineID, path);
point = new Point();
previousPointMap.put(lineID, point);
}
path.moveTo(x, y);
point.x = (int) x;
point.y = (int) y;
}
private void touchMoved(MotionEvent event) {
for (int i = 0; i < event.getPointerCount(); i++) {
// luetaan pointtein id ja indeksi
int pointerID = event.getPointerId(i);
int pointerIndex = event.findPointerIndex(pointerID);
if (pathMap.containsKey(pointerID)) {
float newX = event.getX(pointerIndex);
float newY = event.getY(pointerIndex);
Path path = pathMap.get(pointerID);
Point point = previousPointMap.get(pointerID);
// lasketaan kuinka kauas liikuttu
float deltaX = Math.abs(newX - point.x);
float deltaY = Math.abs(newY - point.y);
if (deltaX >= TOUCH_TOLERANCE || deltaY >= TOUCH_TOLERANCE) {
path.quadTo(point.x, point.y, (newX + point.x) / 2,
(newY + point.y) / 2);
point.x = (int) newX;
point.y = (int) newY;
}
}
}
}
private void touchEnded(int lineID) {
Path path = pathMap.get(lineID);
bitmapCanvas.drawPath(path, paintLine);
path.reset(); // tyhjennetään polku
}
public void saveImage() {
final String name = "Doodlz" + System.currentTimeMillis() + ".jpg";
String location = MediaStore.Images.Media.insertImage(
getContext().getContentResolver(), bitmap, name,
"Doodlz Drawing"
);
if (location != null) {
Toast message = Toast.makeText(getContext(),
R.string.message_saved,
Toast.LENGTH_SHORT);
message.setGravity(Gravity.CENTER, message.getXOffset() / 2,
message.getYOffset() / 2);
message.show();
}
else {
Toast message = Toast.makeText(getContext(),
R.string.message_error_saving, Toast.LENGTH_SHORT);
message.setGravity(Gravity.CENTER, message.getXOffset() / 2,
message.getYOffset() / 2);
message.show();
}
}
public void printImage() {
if (PrintHelper.systemSupportsPrint()) {
PrintHelper printHelper = new PrintHelper(getContext());
printHelper.setScaleMode(printHelper.SCALE_MODE_FIT);
printHelper.printBitmap("Doodlz Imate", bitmap);
}
else {
Toast message = Toast.makeText(getContext(),
R.string.message_error_printing, Toast.LENGTH_SHORT);
message.setGravity(Gravity.CENTER, message.getXOffset() / 2,
message.getYOffset() / 2);
message.show();
}
}
}
And here is the code of a LineWidthFragment class:
package com.esimerkki.doodl2;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
//import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import androidx.fragment.app.DialogFragment;
public class LineWidthFragment extends DialogFragment {
private ImageView widthImageView;
#Override
public Dialog onCreateDialog(Bundle bundle) {
AlertDialog.Builder builder =
new AlertDialog.Builder(getActivity());
View lineWidthDialogView =
getActivity().getLayoutInflater().inflate(
R.layout.fragment_line_width, null);
builder.setView(lineWidthDialogView); // lisätään GUI dialogiin
builder.setTitle(R.string.title_line_width_dialog);
widthImageView = (ImageView) lineWidthDialogView.findViewById(
R.id.widthImageView);
final DoodleView doodleView = getDoodleFragment().getDoodleView();
final SeekBar widthSeekBar = (SeekBar)
lineWidthDialogView.findViewById(R.id.widthSeekBar);
widthSeekBar.setOnSeekBarChangeListener(lineWidthChanged);
widthSeekBar.setProgress(doodleView.getLineWidth());
builder.setPositiveButton(R.string.button_set_line_width,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
doodleView.setLineWidth(widthSeekBar.getProgress());
}
}
);
return builder.create();
}
private FirstFragment getDoodleFragment() {
return (FirstFragment) getChildFragmentManager().findFragmentById(
R.id.doodleFragment);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
FirstFragment fragment = getDoodleFragment();
if (fragment != null)
fragment.setDialogOnScreen(true);
}
#Override
public void onDetach() {
super.onDetach();
FirstFragment fragment = getDoodleFragment();
if (fragment != null)
fragment.setDialogOnScreen(false);
}
private final OnSeekBarChangeListener lineWidthChanged =
new OnSeekBarChangeListener() {
final Bitmap bitmap = Bitmap.createBitmap(
400, 100, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap); // piirtää bittikarttaan
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
Paint p = new Paint();
p.setColor(
getDoodleFragment().getDoodleView().getDrawingColor());
p.setStrokeCap(Paint.Cap.ROUND);
p.setStrokeWidth(progress);
bitmap.eraseColor(
getResources().getColor(android.R.color.transparent,
getContext().getTheme()));
canvas.drawLine(30, 50, 370, 50, p);
widthImageView.setImageBitmap(bitmap);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { // tarvitaan
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) { // tarvitaan
}
};
}
Your error says the following:
null object reference
This means that 1 object gives the value 0.
Your code looks fine but if you rewrite the code once again you may solve the mistake.
It is caused by a pitty error in your code.
When rewriting it. You can find that error.
Even if this was a bug with some plugin or anything else.
Also after you rewrote it, if you get the same error then you need to look onto a reference.
In my SurfaceView when I click on the screen it creates black dots after that I connect them and it has a filled with color. After that I am ttrying to draw other bitmap and I want the current state be something like a background and when I touch the screen I want to draw a bitmap on this possition and when I am trying to draw a bitmap on touch location the canvas goes back to the previous state with the draws.
Here is my code:
package com.inveitix.android.clue.ui.views;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.inveitix.android.clue.R;
import com.inveitix.android.clue.cmn.Door;
import com.inveitix.android.clue.cmn.MapPoint;
import java.util.ArrayList;
import java.util.List;
public class DrawingView extends SurfaceView {
private static final String TAG = "DrawingView";
private static final float DOOR_SIZE = 30;
private Paint paint;
private Canvas canvas;
private int maxHeight;
private int maxWidth;
private SurfaceHolder surfaceHolder;
private List<MapPoint> shape;
private List<Door> doors;
private float ratio;
private boolean isFloorFinished;
private boolean isDoorSelected;
Path path;
public DrawingView(Context context) {
super(context);
init();
}
public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void setIsDoorSelected(boolean isDoorSelected) {
this.isDoorSelected = isDoorSelected;
}
public void setIsFloorFinished(boolean isFloorFinished) {
this.isFloorFinished = isFloorFinished;
}
private void init() {
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
isFloorFinished = false;
surfaceHolder = this.getHolder();
prepareCanvas();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
shape = new ArrayList<>();
doors = new ArrayList<>();
}
private void prepareCanvas() {
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
}
public void surfaceCreated(SurfaceHolder holder) {
canvas = holder.lockCanvas();
canvas.drawColor(Color.WHITE);
holder.unlockCanvasAndPost(canvas);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
});
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
int minh = getPaddingBottom() + getPaddingTop() + getSuggestedMinimumHeight();
this.maxWidth = resolveSizeAndState(minw, widthMeasureSpec, 1);
this.maxHeight = resolveSizeAndState(minh, heightMeasureSpec, 1);
if (ratio != 0) {
maxHeight = (int) (maxWidth / ratio);
}
Log.i(TAG, "onMeasure width:" + maxWidth);
Log.i(TAG, "onMeasure height:" + maxHeight);
setMeasuredDimension(maxWidth, maxHeight);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN && !isFloorFinished) {
if (surfaceHolder.getSurface().isValid()) {
shape.add(new MapPoint(event.getX(), event.getY()));
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
for (MapPoint point : shape) {
canvas.drawCircle(point.getX(), point.getY(), 10, paint);
}
surfaceHolder.unlockCanvasAndPost(canvas);
}
} else if (event.getAction() == MotionEvent.ACTION_DOWN && isDoorSelected) {
if (surfaceHolder.getSurface().isValid()) {
Door door = new Door();
door.setConnectedTo("door1"); //this is for test
door.setX(event.getX());
door.setY(event.getY());
doors.add(door);
canvas = surfaceHolder.lockCanvas();
drawDoors(canvas);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
return false;
}
public void drawFloor() {
Bitmap bmpFloorPattern = BitmapFactory.decodeResource(getResources(), R.drawable.floor_pattern6);
BitmapShader patternBMPshader = new BitmapShader(bmpFloorPattern,
Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
canvas = surfaceHolder.lockCanvas();
path = new Path();
path.reset();
if (shape != null) {
path.moveTo(shape.get(0).getX(), shape.get(0).getY());
alignPoints(path);
canvas.drawColor(Color.WHITE);
for (int i = 0; i < shape.size(); i++) {
path.lineTo(shape.get(i).getX(), shape.get(i).getY());
}
}
paint.setShader(patternBMPshader);
path.close();
canvas.drawPath(path, paint);
paint.setShader(null);
surfaceHolder.unlockCanvasAndPost(canvas);
}
public void drawDoors(Canvas canvas) {
Bitmap bmpDoor = BitmapFactory.decodeResource(getResources(), R.drawable.door32);
paint.setFilterBitmap(true);
if (doors != null && doors.size() > 0) {
for (Door door : doors) {
canvas.drawBitmap(bmpDoor, door.getX() - DOOR_SIZE, door.getY() - DOOR_SIZE, null);
}
}
}
private void alignPoints(Path path) {
MapPoint previousPoint = null;
for (int i = 0; i < shape.size(); i++) {
float x = shape.get(i).getX();
float y = shape.get(i).getY();
if (previousPoint != null) {
float deltaX = Math.abs(x - previousPoint.getX());
float deltaY = Math.abs(y - previousPoint.getY());
if (Math.max(deltaX, deltaY) == deltaX) {
x = previousPoint.getX();
} else {
y = previousPoint.getY();
}
}
path.lineTo(x, y);
previousPoint = shape.get(i);
}
}
public void setWidthToHeightRatio(float ratio) {
this.ratio = ratio;
maxHeight = (int) (maxWidth / ratio);
invalidate();
requestLayout();
}
}
Any ideas how to draw over the drawn background ?
I found it I have to draw doors in the same time with the floor so I did this changes:
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN && !isFloorFinished) {
if (surfaceHolder.getSurface().isValid()) {
shape.add(new MapPoint(event.getX(), event.getY()));
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
for (MapPoint point : shape) {
canvas.drawCircle(point.getX(), point.getY(), 10, paint);
}
surfaceHolder.unlockCanvasAndPost(canvas);
}
} else if (event.getAction() == MotionEvent.ACTION_DOWN && isDoorSelected) {
if (surfaceHolder.getSurface().isValid()) {
Door door = new Door();
door.setConnectedTo("door1"); //this is for test
door.setX(event.getX());
door.setY(event.getY());
doors.add(door);
drawFloor();
}
}
return false;
}
public void drawFloor() {
Bitmap bmpFloorPattern = BitmapFactory.decodeResource(getResources(), R.drawable.floor_pattern6);
BitmapShader patternBMPshader = new BitmapShader(bmpFloorPattern,
Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
canvas = surfaceHolder.lockCanvas();
path = new Path();
path.reset();
if (shape != null) {
path.moveTo(shape.get(0).getX(), shape.get(0).getY());
alignPoints(path);
canvas.drawColor(Color.WHITE);
for (int i = 0; i < shape.size(); i++) {
path.lineTo(shape.get(i).getX(), shape.get(i).getY());
}
}
paint.setShader(patternBMPshader);
path.close();
canvas.drawPath(path, paint);
paint.setShader(null);
if(doors.size() > 0) {
drawDoors();
}
surfaceHolder.unlockCanvasAndPost(canvas);
}
I am trying to create the circular image view. After searching google I have tried something but its not working.
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
class WheelItemView extends ImageView {
private int _index;
private float _x;
private float _y;
private int _width;
private int _height;
private boolean _drawn;
private float _currentAngle;
private Paint paint;
private Paint paintBorder;
private int borderWidth;
private boolean _hasRotation = false;
private float _dx=0;
private float _dy=0;
private Bitmap image;
private int canvasSize;
public WheelItemView(Context context) {
this(context, null);
}
public WheelItemView(Context context, AttributeSet attrs) {
this(context, attrs, in.eaft.byoo.R.attr.circularImageViewStyle);
// this(context, attrs, 0);
}
public WheelItemView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
paint = new Paint();
paint.setAntiAlias(true);
paintBorder = new Paint();
paintBorder.setAntiAlias(true);
// load the styled attributes and set their properties
TypedArray attributes = context.obtainStyledAttributes(attrs, in.eaft.byoo.R.styleable.CircularImageView, defStyle, 0);
if(attributes.getBoolean(in.eaft.byoo.R.styleable.CircularImageView_border, true)) {
int defaultBorderSize = (int) (4 * getContext().getResources().getDisplayMetrics()
.density + 0.5f);
setBorderWidth(attributes.getDimensionPixelOffset(in.eaft.byoo.R.styleable.
CircularImageView_border_width, defaultBorderSize));
setBorderColor(attributes.getColor(in.eaft.byoo.R.styleable.CircularImageView_border_color,
Color.WHITE));
}
if(attributes.getBoolean(in.eaft.byoo.R.styleable.CircularImageView_shadow, true))
addShadow();
}
private void addShadow() {
setLayerType(LAYER_TYPE_SOFTWARE, paintBorder);
paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK);
}
private void setBorderColor(int color) {
if(paintBorder != null)
paintBorder.setColor(color);
this.invalidate();
}
private void setBorderWidth(int borderWidth) {
this.borderWidth = borderWidth;
this.requestLayout();
this.invalidate();
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
/*_width= measureWidth(widthMeasureSpec);
_height = measureHeight(heightMeasureSpec);*/
setMeasuredDimension(_width, _height);
}
private int measureHeight(int measureSpecHeight) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpecHeight);
int specSize = MeasureSpec.getSize(measureSpecHeight);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = canvasSize;
}
return (result + 2);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// The parent has determined an exact size for the child.
result = specSize;
} else if (specMode == MeasureSpec.AT_MOST) {
// The child can be as large as it wants up to the specified size.
result = specSize;
} else {
// The parent has not imposed any constraint on the child.
result = canvasSize;
}
return result;
}
#Override
public void setImageBitmap(Bitmap src)
{
_width = src.getWidth();
_height = src.getHeight();
if(_hasRotation) {
calculateDistance();
}
super.setImageBitmap(src);
}
#Override
protected void onDraw(Canvas canvas)
{
//if(_hasRotation) {
/*Drawable d = getDrawable();
if(d!=null && d instanceof BitmapDrawable && ((BitmapDrawable)d).getBitmap()!=null) {
Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
canvas.save();
canvas.translate(_dx, _dy);
canvas.rotate(_currentAngle+90, _width/2f, _height/2f);
// canvas.drawText(text, 0, 0, p);
canvas.drawBitmap(((BitmapDrawable)d).getBitmap(),0, 0, p);
canvas.restore();
return;
}*/
System.out.println("get drawable is null : " + (getDrawable() == null));
image = drawableToBitmap(getDrawable());
// init shader
if (image != null) {
canvasSize = canvas.getWidth();
if(canvas.getHeight()<canvasSize)
canvasSize = canvas.getHeight();
BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize,
canvasSize, false),
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
paint.setShader(shader);
// circleCenter is the x or y of the view's center
// radius is the radius in pixels of the cirle to be drawn
// paint contains the shader that will texture the shape
int circleCenter = (canvasSize - (borderWidth * 2)) / 2;
canvas.save();
// canvas.translate(_dx, _dy);
canvas.rotate(_currentAngle+90, _width/2f, _height/2f);
canvas.drawCircle(_width-_dx, _height-_dy/2,
borderWidth * 10, paintBorder);
canvas.drawCircle(_width-_dx, _height-_dy/2,
borderWidth * 10, paint);
/*canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth,
((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder);
canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth,
((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint);*/
canvas.restore();
// }
}
super.onDraw(canvas);
}
private Bitmap drawableToBitmap(Drawable drawable) {
if (drawable == null) {
return null;
} else if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
Bitmap bitmap = Bitmap.createBitmap(70,
70, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
private void calculateDistance()
{
_dx = (float) ((Math.sqrt(_width*_width + _height*_height)-_width)/2.0f);
_dy = (float) ((Math.sqrt(_width*_width + _height*_height)-_height)/2.0f);
}
public void setIndex(int index)
{
this._index = index;
}
public int getIndex()
{
return _index;
}
public void setCurrentAngle(float currentAngle)
{
this._currentAngle = currentAngle;
}
public float getCurrentAngle()
{
return _currentAngle;
}
public void setAxisX(float x)
{
this._x = x;
}
public float getAxisX()
{
return _x;
}
public void setAxisY(float y)
{
this._y = y;
}
public float getAxisY()
{
return _y;
}
public void setDrawn(boolean drawn)
{
this._drawn = drawn;
}
public boolean isDrawn()
{
return _drawn;
}
public void setItemWidth(int _width)
{
this._width = _width;
}
public float getItemWidth()
{
return _width;
}
public void setItemHeight(int _height)
{
this._height = _height;
}
public float getItemHeight()
{
return _height;
}
public int getDistanceX()
{
return (int)_dx;
}
public int getDistanceY()
{
return (int)_dy;
}
public void setRotatedItem(Boolean flag)
{
_hasRotation = flag;
if(_hasRotation && (_dx==0 || _dy ==0)) {
calculateDistance();
}
if(!_hasRotation) {
_dx = _dy = 0;
}
}
}
My images are not circular.Instead part of circle is being displayed behind the square image.
can anyone tell me what mistake I have done?
I think ur asking for this
jst create a shape in res>drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" >
<solid android:color="#a7a7a7" />
<stroke android:width="1dp" android:color="#818181" />
</shape>
and use this shape in ur imageview
I am trying to be able to select/highlight a specific grid position onTouch.
Basically, I have an image, with a canvas/bitmap over layering the top of the image, I want to be able to click on a point of the image, and have that box become highlighted(first step is highlighting the grid, I will perform other algorithms on this later on)..
Here is the code for what I have now.. I am able to grab the x y coordinates, but I do not know how to associate the x y coordinates with the grid position.
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
public class ImageWithGridView extends View {
private int rows = 12;
private int columns = 12;
private float width;
private float height;
public static final String TAG="ImageWithGridView";
private static final String SELX = "selX";
private static final String SELY = "selY";
private static final String VIEW_STATE = "viewState";
//private static final int ID = 92;
private int selX; //X index of selection
private int selY; //Y index of selection
private final Bitmap bitmap;
public ImageWithGridView(Context context) {
super(context);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
//use your own image file name, instead of mobot_spring
}
public ImageWithGridView(Context context, AttributeSet attrs){
super(context, attrs);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
//TODO Auto-generated constructor sub
}
public ImageWithGridView(Context context, AttributeSet attrs, int defStyle) {
super (context, attrs, defStyle);
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample);
//TODO Auto-generated constructor stub
}
#Override
protected Parcelable onSaveInstanceState() {
Parcelable p = super.onSaveInstanceState();
Log.d(TAG, "onSaveInstanceState");
Bundle bundle = new Bundle();
bundle.putInt(SELX, selY);
bundle.putInt(SELY, selY);
bundle.putParcelable(VIEW_STATE, p);
return bundle;
}
#Override
protected void onRestoreInstanceState(Parcelable state) {
Log.d(TAG, "onRestoreInstanceState");
Bundle bundle = (Bundle) state;
selX = bundle.getInt(SELX);
selY = bundle.getInt(SELY);
super.onRestoreInstanceState(bundle.getParcelable(VIEW_STATE));
return;
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
//adjust the ratio for width and height here:
this.setMeasuredDimension(parentWidth, parentHeight*2/3);
}
#Override
protected void onSizeChanged(int newWidth, int newHeight, int oldw, int oldh) {
width = newWidth / (float) columns;
height = newHeight / (float)rows;
Log.d(TAG, "~~~~~~~~~~~onSizeChanged: width " + width + ", height " + height);
super.onSizeChanged(newWidth, newWidth, oldw, oldh);
}
#Override
protected void onDraw(Canvas canvas) {
RectF dst = new RectF(width, height, (columns-1) * width, (rows - 1) * height);
//Draw the background...
Paint background = new Paint();
background.setColor(getResources().getColor(R.color.background));
Log.d(TAG, "~~~~~~~~~10 ");
canvas.drawRect(0, 0, getWidth(), getHeight(), background);
Log.d(TAG, "~~~~~~~~~20 ");
canvas.drawBitmap(bitmap, null, dst, null);
Log.d(TAG, "~~~~~~~~~30 ");
//Define colors for the grid lines
Paint dark = new Paint();
dark.setColor(getResources().getColor(R.color.dark));
Paint hilite = new Paint();
hilite.setColor(getResources().getColor(R.color.hilite));
Paint light = new Paint();
light.setColor(getResources().getColor(R.color.light));
//Draw the minor grid lines
for (int i = 0; i < rows; i++) {
canvas.drawLine(0, i * height-1, getWidth(), i * height-1, dark);
canvas.drawLine(0, i * height, getWidth(), i * height, light);
canvas.drawLine(0, i * height + 1, getWidth(), i * height + 1, hilite);
}
for (int i=0; i<columns; i++) {
canvas.drawLine(i * width-1, 0, i* width-1, getHeight(), dark);
canvas.drawLine(i * width, 0, i * width, getHeight(), light);
canvas.drawLine(i * width + 1, 0, i* width + 1, getHeight(), hilite);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() != MotionEvent.ACTION_DOWN){
return super.onTouchEvent(event);
}
selX = (int) event.getX();
selY = (int) event.getY();
Log.d(TAG, "onTouchEvent: x " + selX + ", y " + selY);
return true;
}
public int getClickedX() {return selX;}
public int getClickedY() {return selY;}
}
This is my other class
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CustomizeImageViewActivity extends Activity{
/** Called when the activity is first created. */
private Button btnShow;
private TextView label;
private ImageWithGridView imgView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setContentView(R.layout.relative_layout);
//setContentView(R.layout.table_layout);
btnShow = (Button) findViewById(R.id.btnShow);
label = (TextView) findViewById(R.id.label);
imgView = (ImageWithGridView)findViewById(R.id.imageView1);
btnShow.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View arg0) {
label.setText("("+imgView.getClickedX() + "," + imgView.getClickedY() + ")");
}
});
}
}
Please advise with any guides/tutorials I should look at.. I have tried doing some research but I have not been able to find anything on this.