How to recognize special markers on image in Android? - android

I want to put buttons on layout by special markers (f.g. small circles).
See picture below:
Final result maybe like this:
Whats the right way to do that? Most libraries and SDKs for image recognition works with images from camera (almost in real time). In my case I have static image and its remain only recognize the special markers and then put buttons.

I found this solve: Detect Circle in image using OpenCV in Android and used it in my project. This works fine, but I have another problem (see this question: How to convert Mat coordinates to Layout coordinates?)
package com.example.aboev.matrix_sample;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.constraint.ConstraintLayout;
import android.support.constraint.ConstraintSet;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import org.opencv.android.Utils;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class FloorPlanActivity extends AppCompatActivity {
Mat matBackground;
Mat grayMatBackground;
int colorChannels = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_floor_plan);
ImageView imageViewFloorPlan = findViewById(R.id.imageViewFloorPlan);
FileInputStream imageFileInputStream;
Context context = this;
// this double dimension array will contain X,Y positions of recognized circles
ArrayList<ArrayList<Integer>> coordinates = new ArrayList<>();
ConstraintLayout layout = findViewById(R.id.scrollingFloorPlanLayout);
try {
imageFileInputStream = context.openFileInput(getString(R.string.png_image_file_name));
Bitmap imageFloorPlan = BitmapFactory.decodeStream(imageFileInputStream);
imageViewFloorPlan.setImageBitmap(imageFloorPlan);
matBackground = new Mat(imageFloorPlan.getHeight(), imageFloorPlan.getWidth(),
CvType.CV_8UC1);
grayMatBackground = new Mat(imageFloorPlan.getHeight(), imageFloorPlan.getWidth(),
CvType.CV_8UC1);
Utils.bitmapToMat(imageFloorPlan, matBackground);
colorChannels = (matBackground.channels() == 3) ?
Imgproc.COLOR_BGR2GRAY : ((matBackground.channels() == 4) ?
Imgproc.COLOR_BGRA2GRAY : 1);
Imgproc.cvtColor(matBackground, grayMatBackground, colorChannels);
Imgproc.GaussianBlur(grayMatBackground, grayMatBackground,
new Size(9, 9), 2, 2);
double dp = 1.5d;
double minDist = grayMatBackground.rows() / 16;
int minRadius = 10;
int maxRadius = 20;
double param1 = 70;
double param2 = 50;
Mat circles = new Mat(imageViewFloorPlan.getWidth(), imageViewFloorPlan.getHeight(),
CvType.CV_8UC1);
Imgproc.HoughCircles(grayMatBackground, circles,
Imgproc.CV_HOUGH_GRADIENT, dp, minDist, param1,
param2, minRadius, maxRadius);
int numberOfCircles = (circles.rows() == 0) ? 0 : circles.cols();
if (circles.empty() || circles.get(0, 0).length == 1) {
Toast.makeText(context, getString(R.string.msg_circles_not_found),
Toast.LENGTH_SHORT).show();
} else {
for (int i=0; i<numberOfCircles; i++) {
double[] circleCoordinates = circles.get(0, i);
final int x = (int) circleCoordinates[0], y = (int) circleCoordinates[1];
Point center = new Point(x, y);
int radius = (int) circleCoordinates[2];
Imgproc.circle(matBackground, center, radius, new Scalar(0,
255, 0), 4);
Imgproc.rectangle(matBackground, new Point(x - 5, y - 5),
new Point(x + 5, y + 5),
new Scalar(0, 128, 255), -1);
coordinates.add( new ArrayList<Integer>() {{ add((int) x); add((int) y); }} );
}
}
Utils.matToBitmap(matBackground, imageFloorPlan);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
imageFileInputStream = context.openFileInput(getString(R.string.table_image_file));
if (!coordinates.isEmpty()) createImgButton(context, BitmapFactory.decodeStream(imageFileInputStream), coordinates);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// This method creates buttons in the centers of recognized circles
private void createImgButton(Context context, Bitmap foregroundImage, ArrayList<ArrayList<Integer>> coordinates) {
ConstraintLayout layout = findViewById(R.id.scrollingFloorPlanLayout);
ConstraintSet constraintSet = new ConstraintSet();
constraintSet.clone(layout);
for (int i = 0; i < coordinates.size(); i++) {
ImageButton btn = new ImageButton(context);
btn.setImageBitmap(foregroundImage);
btn.setId(ViewIdGenerator.generateViewId());
layout.addView(btn);
constraintSet.clone(layout);
// I tried to get real coordinate like this:
double x = (coordinates.get(i).get(1) * 1080) / 480;
double y = (coordinates.get(i).get(0) * 1920) / 640;
constraintSet.connect(btn.getId(), constraintSet.TOP, layout.getId(), constraintSet.TOP, (int) x);
constraintSet.connect(btn.getId(), constraintSet.START, layout.getId(), constraintSet.START, (int) y);
constraintSet.applyTo(layout);
}
}
}
It looks like this:

Related

In Android OpenCV Color Blob Detector is crashing by giving fatal error

I'm using Color Blob detector Sample code of OpenCV (Sample Code), but app is crashing at Core.multiply(contour, new Scalar(4,4), contour); giving some fatal error
libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0x0 in tid 11016 (Thread-4857)
and detailed Log is available to get idea of exact reason. In some other part of code I was using Core.add(fg, bg, markers); and app was giving same fatal error there as well. What is the issue? Please guide towards the solution. I 'm using openCV(3.1)
Code is as following:
package com.iu.kamraapp.utils;
import android.util.Log;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Scalar;
import org.opencv.imgproc.Imgproc;
public class ColorBlobDetector {
// Lower and Upper bounds for range checking in HSV color space
private Scalar mLowerBound = new Scalar(0);
private Scalar mUpperBound = new Scalar(0);
// Minimum contour area in percent for contours filtering
private static double mMinContourArea = 0.1;
// Color radius for range checking in HSV color space
private Scalar mColorRadius = new Scalar(25,50,50,0);
private Mat mSpectrum = new Mat();
private List<MatOfPoint> mContours = new ArrayList<MatOfPoint>();
// Cache
Mat mPyrDownMat = new Mat();
Mat mHsvMat = new Mat();
Mat mMask = new Mat();
Mat mDilatedMask = new Mat();
Mat mHierarchy = new Mat();
public void setColorRadius(Scalar radius) {
mColorRadius = radius;
}
public void setHsvColor(Scalar hsvColor) {
double minH = (hsvColor.val[0] >= mColorRadius.val[0]) ? hsvColor.val[0]-mColorRadius.val[0] : 0;
double maxH = (hsvColor.val[0]+mColorRadius.val[0] <= 255) ? hsvColor.val[0]+mColorRadius.val[0] : 255;
mLowerBound.val[0] = minH;
mUpperBound.val[0] = maxH;
mLowerBound.val[1] = hsvColor.val[1] - mColorRadius.val[1];
mUpperBound.val[1] = hsvColor.val[1] + mColorRadius.val[1];
mLowerBound.val[2] = hsvColor.val[2] - mColorRadius.val[2];
mUpperBound.val[2] = hsvColor.val[2] + mColorRadius.val[2];
mLowerBound.val[3] = 0;
mUpperBound.val[3] = 255;
Mat spectrumHsv = new Mat(1, (int)(maxH-minH), CvType.CV_8UC3);
for (int j = 0; j < maxH-minH; j++) {
byte[] tmp = {(byte)(minH+j), (byte)255, (byte)255};
spectrumHsv.put(0, j, tmp);
}
Imgproc.cvtColor(spectrumHsv, mSpectrum, Imgproc.COLOR_HSV2RGB_FULL, 4);
}
public Mat getSpectrum() {
return mSpectrum;
}
public void setMinContourArea(double area) {
mMinContourArea = area;
}
public void process(Mat rgbaImage) {
try {
Imgproc.pyrDown(rgbaImage, mPyrDownMat);
Imgproc.pyrDown(mPyrDownMat, mPyrDownMat);
Imgproc.cvtColor(mPyrDownMat, mHsvMat, Imgproc.COLOR_RGB2HSV_FULL);
Core.inRange(mHsvMat, mLowerBound, mUpperBound, mMask);
Imgproc.dilate(mMask, mDilatedMask, new Mat());
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(mDilatedMask, contours, mHierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE);
// Find max contour area
double maxArea = 0;
Iterator<MatOfPoint> each = contours.iterator();
while (each.hasNext()) {
MatOfPoint wrapper = each.next();
double area = Imgproc.contourArea(wrapper);
if (area > maxArea)
maxArea = area;
}
// Filter contours by area and resize to fit the original image size
mContours.clear();
each = contours.iterator();
while (each.hasNext()) {
MatOfPoint contour = each.next();
if (Imgproc.contourArea(contour) > mMinContourArea * maxArea) {
Core.multiply(contour, new Scalar(4, 4), contour); // issue is here
mContours.add(contour);
}
}
}
catch (Exception e) { e.printStackTrace(); }
}
public List<MatOfPoint> getContours() {
return mContours;
}
}
package com.iu.kamraapp;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import com.iu.kamraapp.utils.AppGlobal;
import com.iu.kamraapp.utils.ColorBlobDetector;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.JavaCameraView;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.util.ArrayList;
import java.util.List;
public class ColorBlobActivity extends AppCompatActivity implements View.OnTouchListener,CameraBridgeViewBase.CvCameraViewListener2 {
private static final String TAG = "MainActivity";
Context context;
int screenWidth, screenHeight;
private CameraBridgeViewBase mOpenCvCameraView;
private boolean mIsColorSelected = false;
private Mat mRgba;
private Scalar mBlobColorRgba;
private Scalar mBlobColorHsv;
private ColorBlobDetector mDetector;
private Mat mSpectrum;
private Size SPECTRUM_SIZE;
private Scalar CONTOUR_COLOR;
BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
mOpenCvCameraView.setOnTouchListener(ColorBlobActivity.this);
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
setContentView(R.layout.activity_main);
screenWidth = AppGlobal.getScreenResolution(context, true);
screenHeight = AppGlobal.getScreenResolution(context, false);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.tutorial1_activity_java_surface_view);
mOpenCvCameraView.setVisibility(SurfaceView.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
screenWidth = AppGlobal.getScreenResolution(context, false);
screenHeight = AppGlobal.getScreenResolution(context, true);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
screenWidth = AppGlobal.getScreenResolution(context, true);
screenHeight = AppGlobal.getScreenResolution(context, false);
}
}
#Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onResume()
{
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_1_0, this, mLoaderCallback);
OpenCVLoader.initDebug(true);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
#Override
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
mDetector = new ColorBlobDetector();
mSpectrum = new Mat();
mBlobColorRgba = new Scalar(255);
mBlobColorHsv = new Scalar(255);
SPECTRUM_SIZE = new Size(200, 64);
CONTOUR_COLOR = new Scalar(255,0,0,255);
}
public void onCameraViewStopped() {
mRgba.release();
}
public boolean onTouch(View v, MotionEvent event) {
try {
int cols = mRgba.cols();
int rows = mRgba.rows();
int xOffset = (mOpenCvCameraView.getWidth() - cols) / 2;
int yOffset = (mOpenCvCameraView.getHeight() - rows) / 2;
int x = (int) event.getX() - xOffset;
int y = (int) event.getY() - yOffset;
Log.i(TAG, "Touch image coordinates: (" + x + ", " + y + ")");
if ((x < 0) || (y < 0) || (x > cols) || (y > rows)) return false;
Rect touchedRect = new Rect();
touchedRect.x = (x > 4) ? x - 4 : 0;
touchedRect.y = (y > 4) ? y - 4 : 0;
touchedRect.width = (x + 4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
touchedRect.height = (y + 4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;
Mat touchedRegionRgba = mRgba.submat(touchedRect);
Mat touchedRegionHsv = new Mat();
Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);
// Calculate average color of touched region
mBlobColorHsv = Core.sumElems(touchedRegionHsv);
int pointCount = touchedRect.width * touchedRect.height;
for (int i = 0; i < mBlobColorHsv.val.length; i++)
mBlobColorHsv.val[i] /= pointCount;
mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);
Log.i(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");
mDetector.setHsvColor(mBlobColorHsv);
Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);
mIsColorSelected = true;
touchedRegionRgba.release();
touchedRegionHsv.release();
} catch (Exception e) { e.printStackTrace(); }
return false; // don't need subsequent touch events
}
#Override
public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
if (mIsColorSelected) {
mDetector.process(mRgba);
List<MatOfPoint> contours = mDetector.getContours();
Log.d(TAG, "Contours count: " + contours.size());
Imgproc.drawContours(mRgba, contours, -1, CONTOUR_COLOR);
Mat colorLabel = mRgba.submat(4, 68, 4, 68);
colorLabel.setTo(mBlobColorRgba);
Mat spectrumLabel = mRgba.submat(4, 4 + mSpectrum.rows(), 70, 70 + mSpectrum.cols());
mSpectrum.copyTo(spectrumLabel);
}
return mRgba;
}
private Scalar converScalarHsv2Rgba(Scalar hsvColor) {
Mat pointMatRgba = new Mat();
Mat pointMatHsv = new Mat(1, 1, CvType.CV_8UC3, hsvColor);
Imgproc.cvtColor(pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);
return new Scalar(pointMatRgba.get(0, 0));
}
}

grabcut image segmentation in android

I am trying to run this code that I found from the net:
package com.opencv.grabcut.android;
import java.io.IOException;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class Grabcut extends Activity implements OnTouchListener {
ImageView imageView;
Bitmap bitmap;
Canvas canvas;
Scalar color = new Scalar(255, 0, 0, 255);
Point tl, br;
int counter;
Bitmap bitmapResult, bitmapBackground;
Mat dst = new Mat();
final String pathToImage = "/mnt/sdcard/gcut.png";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grabcut_main);
imageView = (ImageView) this.findViewById(R.id.imageView);
bitmap = BitmapFactory.decodeFile(pathToImage);
Toast msg = Toast.makeText(Grabcut.this, "Press top left and bottom right of the foreground image", Toast.LENGTH_LONG);
msg.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
msg.show();
bitmapResult = bitmap.copy(bitmap.getConfig(), true);
canvas = new Canvas(bitmapResult);
imageView.setImageBitmap(bitmapResult);
imageView.setOnTouchListener(this);
tl = new Point();
br = new Point();
counter = 0;
}
//#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (counter == 0) {
tl.x = event.getX();
tl.y = event.getY();
counter++;
} else if (counter == 1) {
br.x = event.getX();
br.y = event.getY();
counter++;
Mat img = new Mat();
img = Highgui.imread(pathToImage);
Mat background = new Mat();
try {
background = Utils.loadResource(getApplicationContext(),
R.drawable.wall );
} catch (IOException e) {
e.printStackTrace();
}
backgroundSubtracting(img, background);
Highgui.imwrite("/mnt/sdcard/GRABCUT/rect.png", dst);
Bitmap jpg = BitmapFactory
.decodeFile("/mnt/sdcard/GRABCUT/rect.png");
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
imageView.setPadding(2, 2, 2, 2);
imageView.setImageBitmap(jpg);
imageView.invalidate();
}
}
return true;
}
private void backgroundSubtracting(Mat img, Mat background) {
Mat firstMask = new Mat();
Mat bgModel = new Mat();
Mat fgModel = new Mat();
Mat mask;
Mat source = new Mat(1, 1, CvType.CV_8U, new Scalar(3.0));
dst = new Mat();
Rect rect = new Rect(tl, br);
Imgproc.grabCut(img, firstMask, rect, bgModel, fgModel, 1, 0 /* GC_INIT_WITH_RECT */);
Core.compare(firstMask, source/* GC_PR_FGD */, firstMask, Core.CMP_EQ);
Mat foreground = new Mat(img.size(), CvType.CV_8UC3, new Scalar(255,
255, 255));
img.copyTo(foreground, firstMask);
Core.rectangle(img, tl, br, color);
Mat tmp = new Mat();
Imgproc.resize(background, tmp, img.size());
background = tmp;
mask = new Mat(foreground.size(), CvType.CV_8UC1, new Scalar(255, 255, 255));
Imgproc.cvtColor(foreground, mask, 6/* COLOR_BGR2GRAY */);
Imgproc.threshold(mask, mask, 254, 255, 1 /* THRESH_BINARY_INV */);
Mat vals = new Mat(1, 1, CvType.CV_8UC3, new Scalar(0.0));
background.copyTo(dst);
background.setTo(vals, mask);
enter code here
Core.add(background, foreground, dst, mask);
firstMask.release();
source.release();
bgModel.release();
fgModel.release();
vals.release();
}
}
There is one error that i don't understand in there
the error goes like this: "wall cannot be resolved or is not a field"
Pardone me if did not explain it clearly, I quite new on android development...
please help.. thanks :)
Copy an image file with file name as "wall.png" under /res/drawable/.
That is suppose to fix the error.

Custom Slider in Infowindow not getting focus - Android Google Map v2

I am trying to create the setting panel at the info window such that we can use the slider inside the info window to adjust something. When it comes to the implementation and execution , I have found that the info window is always gaining the onclick focus. There are n NO any responses by clicking the sliders inside the info window. Woudl you please tell me how to make slider controls to be focused when the user clicks and drag the info windows
?
The below is my code :
package com.larry.proto.maptest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader.TileMode;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
public class MainActivity extends FragmentActivity implements LocationListener {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
Location myLocation;
LocationManager lm;
private ArrayList<Checkpoint> cpList = new ArrayList<Checkpoint> ();
private ArrayList<Marker> thisMarkerList = new ArrayList<Marker> ();
private List<LatLng> ppoints = new ArrayList<LatLng> ();
private int requestCode;
private LatLng globalPoint;
private String infoDesp;
private String infoLat;
private String infoLong;
private Marker mSelectedMarker;
private boolean mRefreshingInfoWindow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
SupportMapFragment sFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
myMap = sFragment.getMap();
myMap.setMyLocationEnabled(true);
myMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
lm = (LocationManager) getSystemService (LOCATION_SERVICE);
String provider = lm.getBestProvider(new Criteria(), true);
Location loc = lm.getLastKnownLocation(provider);
if(loc!=null)
{
onLocationChanged(loc);
}
SharedPreferences prefs = getApplicationContext().getSharedPreferences("MyPref", 0);
String restoredLat = prefs.getString("lat", null);
String restoredLng = prefs.getString("lng", null);
String restoredText = prefs.getString("title", null);
myMap.setOnMapLongClickListener(setting());
myMap.getUiSettings().setRotateGesturesEnabled(false);
if(null!=restoredText){
double lat = null!=restoredLat ? Double.parseDouble(restoredLat) : null;
double lng = null!= restoredLng ? Double.parseDouble(restoredLng) : null;
LatLng posi = new LatLng(lat, lng);
myMap.addMarker(new MarkerOptions().position(posi).title(restoredText)
.snippet(String.valueOf(restoredLat) + "," +
String.valueOf(restoredLng))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
CameraPosition cameraPosition = new CameraPosition.Builder().target(posi).zoom(14).build();
myMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
private OnMapLongClickListener setting() {
// TODO Auto-generated method stub
return new OnMapLongClickListener(){
#Override
public void onMapLongClick(LatLng point) {
// TODO Auto-generated method stub
globalPoint = point;
requestCode = 0;
Intent mIntent = new Intent();
mIntent.setClass(MainActivity.this, SliderActivity.class);
startActivityForResult(mIntent, requestCode);
}};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if (resultCode == ConnectionResult.SUCCESS) {
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS", Toast.LENGTH_LONG)
.show();
} else {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
RQS_GooglePlayServices);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latlng = new LatLng(location.getLatitude() , location.getLongitude());
myMap.moveCamera(CameraUpdateFactory.newLatLng(latlng));
myMap.animateCamera(CameraUpdateFactory.zoomTo(11));
}
private void addMarkersToMap() {
myMap.clear();
ppoints.clear();
LatLng ll;
for (int i = 0; i < cpList.size(); i++) {
ll = new LatLng(cpList.get(i).getPoint().latitude, cpList.get(i).getPoint().longitude);
ppoints.add(ll);
}
int length = ppoints.size();
LatLng first = null ;
if(length >2){
for( int i = 0 ; i < ppoints.size() -1 ; i++){
first = ppoints.get(0);
LatLng pt = ppoints.get(i);
LatLng ptNext = ppoints.get(i+1);
DrawArrowHead(myMap, pt, ptNext , Color.RED , cpList.get(i).getDesp() , i+1 , true);
createDashedLine(myMap, pt, ptNext , Color.RED);
}
List<LatLng> current = ppoints.subList(ppoints.size()-2, ppoints.size());
for( int i = 0 ; i < current.size() -1 ; i++){
first = ppoints.get(0);
LatLng pt = current.get(i);
LatLng ptNext = current.get(i+1);
DrawArrowHead(myMap, pt, ptNext , Color.BLUE , cpList.get(i).getDesp() ,i+1 , false);
createDashedLine(myMap, pt, ptNext , Color.BLUE);
}
myMap.addMarker(new MarkerOptions().position(new LatLng(first.latitude ,
first.longitude )).title("Starting Point")
.snippet(String.valueOf(first.latitude) + "," +
String.valueOf(first.longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}else if( length ==1){
for( int i = 0 ; i < ppoints.size() ; i++){
myMap.addMarker(new MarkerOptions().position(new LatLng(ppoints.get(i).latitude ,
ppoints.get(i).longitude )).title("Starting Point")
.snippet(String.valueOf(ppoints.get(i).latitude) + "," +
String.valueOf(ppoints.get(i).longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
}
else{
myMap.addPolyline(new PolylineOptions().width(5).color(Color.BLUE).addAll(ppoints));
for( int i = 0 ; i < ppoints.size() -1 ; i++){
first = ppoints.get(0);
LatLng pt = ppoints.get(i);
LatLng ptNext = ppoints.get(i+1);
DrawArrowHead(myMap, pt, ptNext , Color.BLUE , cpList.get(i).getDesp() , i+1 , true);
createDashedLine(myMap, pt, ptNext , Color.BLUE);
}
myMap.addMarker(new MarkerOptions().position(new LatLng(first.latitude ,
first.longitude )).title("Starting Point")
.snippet(String.valueOf(first.latitude) + "," +
String.valueOf(first.longitude))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
}
}
private final double degreesPerRadian = 180.0 / Math.PI;
private void DrawArrowHead(GoogleMap mMap, LatLng from, LatLng to , int color, String desp , int number , boolean boolR){
double bearing = GetBearing(from, to);
double adjBearing = Math.round(bearing / 3) * 3;
while (adjBearing >= 120) {
adjBearing -= 120;
}
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL url;
Bitmap image = null;
try {
String name = "dir_" + String.valueOf((int)adjBearing) + ".png";
String link = "http://www.google.com/intl/en_ALL/mapfiles/" + name;
Log.d("ling k" , link);
url = new URL(link);
try {
String imageName = link.substring(link.lastIndexOf("/"), link.length());
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + imageName );
if(!file.exists()){
startService(new Intent(MainActivity.this , ImageIntentService.class).putExtra("urlpath", link));
Options mBitmapOptions = new BitmapFactory.Options();
mBitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;
mBitmapOptions.inDither = true;
mBitmapOptions.inPurgeable = true;
mBitmapOptions.inInputShareable = true;
Rect rec = new Rect();
rec.set(-1, -1, -1, -1);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream() , rec , mBitmapOptions);
image = getResizedBitmap(image , image.getHeight()*2 , image.getWidth()*2);
}else{
Options mBitmapOptions = new BitmapFactory.Options();
mBitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_4444;
mBitmapOptions.inDither = true;
mBitmapOptions.inPurgeable = true;
mBitmapOptions.inInputShareable = true;
Rect rec = new Rect();
rec.set(-1, -1, -1, -1);
try {
image = BitmapFactory.decodeStream(new FileInputStream(file), null, mBitmapOptions);
image = getResizedBitmap(image , image.getHeight()*2 , image.getWidth()*2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (image != null){
float anchorX = 0.5f;
float anchorY = 0.5f;
int offsetX = 0;
int offsetY = 0;
int width = image.getWidth();
int height = image.getHeight();
if (bearing >= 292.5 && bearing < 335.5){
offsetX = 24;
offsetY = 24;
offsetX = width;
offsetY = height;
}
else if (bearing >= 247.5 && bearing < 292.5){
offsetX = 24;
offsetY = 12;
offsetX = width;
offsetY = height/2;
}
else if (bearing >= 202.5 && bearing < 247.5){
offsetX = 24;
offsetY = 0;
offsetX = width;
offsetY = 0;
}
else if (bearing >= 157.5 && bearing < 202.5){
offsetX = 12;
offsetY = 0;
offsetX = width/2;
offsetY = 0;
}
else if (bearing >= 112.5 && bearing < 157.5){
offsetX = 0;
offsetY = 0;
}
else if (bearing >= 67.5 && bearing < 112.5){
offsetX = 0;
offsetY = 12;
offsetX = 0;
offsetY = height/2;
}
else if (bearing >= 22.5 && bearing < 67.5){
offsetX = 0;
offsetY = 24;
offsetX = 0;
offsetY = height;
}
else {
offsetX = 12;
offsetY = 24;
offsetX = width/2;
offsetY = height;
}
Bitmap wideBmp;
Canvas wideBmpCanvas;
Rect src, dest;
wideBmp = Bitmap.createBitmap(image.getWidth() *2, image.getHeight() * 2, image.getConfig());
wideBmpCanvas = new Canvas(wideBmp);
src = new Rect(0, 0, image.getWidth(), image.getHeight());
dest = new Rect(src);
dest.offset(offsetX, offsetY);
Paint maskedPaint = new Paint();
int r = Color.red(color);
int g = Color.green(color);
int b = Color.blue(color);
ColorMatrix cm = new ColorMatrix();
cm.set(new float[] {
1, 0, 0, 0, r,
0, 1, 0, 0, g,
0, 0, 1, 0, b,
0, 0, 0, 1, 0 }); // last line is antialias
maskedPaint.setColorFilter(new ColorMatrixColorFilter(cm));
maskedPaint.setShader(new BitmapShader(image, TileMode.REPEAT, TileMode.REPEAT));
// color
wideBmpCanvas.drawBitmap(image, src, dest, maskedPaint);
if(boolR == true){
Paint stroke = new Paint();
stroke.setColor(Color.YELLOW);
stroke.setAntiAlias(false);
stroke.setStrokeWidth(8);
stroke.setTextSize(60);
wideBmpCanvas.drawText(String.valueOf(number),
(float)wideBmpCanvas.getWidth()/2, (float)wideBmpCanvas.getHeight()/2, stroke);
}
infoDesp = desp;
infoLat =String.valueOf(to.latitude);
infoLong = String.valueOf(to.longitude);
mMap.setInfoWindowAdapter(new CustomInfoAdapter());
mMap.addMarker(new MarkerOptions()
.position(to).title(desp)
.snippet(String.valueOf(to.latitude) + "," + String.valueOf(to.longitude))
.icon(BitmapDescriptorFactory.fromBitmap(wideBmp))
.anchor(anchorX, anchorY));
}
}
class CustomInfoAdapter implements InfoWindowAdapter{
#Override
public View getInfoContents(Marker arg0) {
View marker = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).
inflate(R.layout.custom_marker_layout, null);
if (!mRefreshingInfoWindow) {
mSelectedMarker = arg0;
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
TextView lat1 = (TextView) marker.findViewById(R.id.textView1);
TextView long1 = (TextView) marker.findViewById(R.id.textView2);
SeekBar sk = (SeekBar) marker.findViewById(R.id.seekBar1);
numTxt.setText(arg0.getTitle());
lat1.setText(String.valueOf(arg0.getPosition().latitude));
long1.setText(String.valueOf(arg0.getPosition().longitude));
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
if(progress==25){
Vibrator v = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
}
}
});
sk.requestFocus();
}else{
refreshInfoWindow();
}
return marker;
}
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
private void refreshInfoWindow() {
if (mSelectedMarker == null) {
return;
}
mRefreshingInfoWindow = true;
mSelectedMarker.showInfoWindow();
mRefreshingInfoWindow = false;
}
}
private double GetBearing(LatLng from, LatLng to){
double lat1 = from.latitude * Math.PI / 180.0;
double lon1 = from.longitude * Math.PI / 180.0;
double lat2 = to.latitude * Math.PI / 180.0;
double lon2 = to.longitude * Math.PI / 180.0;
double angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ),
Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
if (angle < 0.0)
angle += Math.PI * 2.0;
angle = angle * degreesPerRadian;
return angle;
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
public void writeToFile(Checkpoint cp , String vertical , String circle , File f){
OutputStreamWriter outStreamWriter = null;
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(f, true);
outStreamWriter = new OutputStreamWriter(outStream);
outStreamWriter.write(new char[]{});
outStreamWriter.append(cp.getDesp());
outStreamWriter.append('\n');
outStreamWriter.append(String.valueOf(cp.getPoint().latitude));
outStreamWriter.append('\n');
outStreamWriter.append(String.valueOf(cp.getPoint().longitude));
outStreamWriter.append('\n');
outStreamWriter.append("the vertical slider value is :" + vertical);
outStreamWriter.append('\n');
outStreamWriter.append("the circle slider value is :" + circle);
outStreamWriter.append('\n');
outStreamWriter.flush();
outStreamWriter.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void createDashedLine(GoogleMap map, LatLng latLngOrig, LatLng latLngDest, int color){
double difLat = latLngDest.latitude - latLngOrig.latitude;
double difLng = latLngDest.longitude - latLngOrig.longitude;
double zoom = map.getCameraPosition().zoom;
double divLat = difLat / (zoom * 2);
double divLng = difLng / (zoom * 2);
LatLng tmpLatOri = latLngOrig;
for(int i = 0; i < (zoom * 2); i++){
LatLng loopLatLng = tmpLatOri;
if(i > 0){
loopLatLng = new LatLng(tmpLatOri.latitude + (divLat * 0.25f), tmpLatOri.longitude + (divLng * 0.25f));
}
Polyline polyline = map.addPolyline(new PolylineOptions()
.add(loopLatLng).add(new LatLng(tmpLatOri.latitude + divLat, tmpLatOri.longitude + divLng))
.color(color).width(5f));
tmpLatOri = new LatLng(tmpLatOri.latitude + divLat, tmpLatOri.longitude + divLng);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode ==0){
if(resultCode ==RESULT_OK){
String change01 = data.getStringExtra("change01");
String change02 = data.getStringExtra("change02");
Toast.makeText(MainActivity.this , change01 + " " + change02 , Toast.LENGTH_SHORT).show();
Checkpoint cp = new Checkpoint("Destination", globalPoint, 0);
Log.d("lati long" , String.valueOf(globalPoint.latitude) + ":" + String.valueOf(globalPoint.longitude));
cpList.add(cp);
File dir = new File( Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator + "NOVAX" );
if(!dir.exists()){
dir.mkdirs();
}
Checkpoint lastlyAdded = cpList.get(cpList.size() -1 );
writeToFile(lastlyAdded , change01 , change02 , new File(dir.getAbsolutePath()+ File.separator + "text.txt" ));
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
editor.clear();
editor.putString("title", lastlyAdded.getDesp());
editor.putString("lat", String.valueOf(lastlyAdded.getPoint().latitude));
editor.putString("lng", String.valueOf(lastlyAdded.getPoint().longitude));
editor.commit();
for(int i = 0 ; i < cpList.size() ; i ++){
Checkpoint cPoint = cpList.get(i);
if(!cPoint.getPoint().equals(lastlyAdded.getPoint())){
cPoint.setState(1);
cPoint.setDesp("Checkpoint "+String.valueOf(i+1) );
}
}
addMarkersToMap();
}
}
}
}
According to Google's documentation, custom info windows are not real windows, but instead a rendered image inserted into the map view. The only items in a google map that can gain focus seem to be the markers themselves. The info windows an take a onClickListener though. Here's the relevant info. Look at the note in the Custom Info Windows section in their docs.
Note: The info window that is drawn is not a live view. The view is rendered as an image (using View.draw(Canvas)) at the time it is returned. This means that any subsequent changes to the view will not be reflected by the info window on the map. To update the info window later (for example, after an image has loaded), call showInfoWindow(). Furthermore, the info window will not respect any of the interactivity typical for a normal view such as touch or gesture events. However you can listen to a generic click event on the whole info window as described in the section below.
There may be a way to use a FrameLayout and a view overtop, acting like a custom info window, but that's more of a hack than a supported solution.

generate barcode and show on ImageView in android

I am new in android development,and I'm working on android with eclipse now.
I want to generate barcode and show it in ImageView by clicking Button.
Use zxing generate barcodes
Follow these steps and you are good to go.
first, locate core.jar under libs folder.
libs/core.jar
You can download ZXing-2.1.zip from here.
http://code.google.com/p/zxing/downloads/
After unzipping the file, find the jar file.
\ZXing-2.1\zxing-2.1\core\core.jar
And then write your own code like below.
import java.util.EnumMap;
import java.util.Map;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
public class BarcodeExampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l = new LinearLayout(this);
l.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
l.setOrientation(LinearLayout.VERTICAL);
setContentView(l);
// barcode data
String barcode_data = "123456";
// barcode image
Bitmap bitmap = null;
ImageView iv = new ImageView(this);
try {
bitmap = encodeAsBitmap(barcode_data, BarcodeFormat.CODE_128, 600, 300);
iv.setImageBitmap(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
l.addView(iv);
//barcode text
TextView tv = new TextView(this);
tv.setGravity(Gravity.CENTER_HORIZONTAL);
tv.setText(barcode_data);
l.addView(tv);
}
/**************************************************************
* getting from com.google.zxing.client.android.encode.QRCodeEncoder
*
* See the sites below
* http://code.google.com/p/zxing/
* http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/EncodeActivity.java
* http://code.google.com/p/zxing/source/browse/trunk/android/src/com/google/zxing/client/android/encode/QRCodeEncoder.java
*/
private static final int WHITE = 0xFFFFFFFF;
private static final int BLACK = 0xFF000000;
Bitmap encodeAsBitmap(String contents, BarcodeFormat format, int img_width, int img_height) throws WriterException {
String contentsToEncode = contents;
if (contentsToEncode == null) {
return null;
}
Map<EncodeHintType, Object> hints = null;
String encoding = guessAppropriateEncoding(contentsToEncode);
if (encoding != null) {
hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, encoding);
}
MultiFormatWriter writer = new MultiFormatWriter();
BitMatrix result;
try {
result = writer.encode(contentsToEncode, format, img_width, img_height, hints);
} catch (IllegalArgumentException iae) {
// Unsupported format
return null;
}
int width = result.getWidth();
int height = result.getHeight();
int[] pixels = new int[width * height];
for (int y = 0; y < height; y++) {
int offset = y * width;
for (int x = 0; x < width; x++) {
pixels[offset + x] = result.get(x, y) ? BLACK : WHITE;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
}
private static String guessAppropriateEncoding(CharSequence contents) {
// Very crude at the moment
for (int i = 0; i < contents.length(); i++) {
if (contents.charAt(i) > 0xFF) {
return "UTF-8";
}
}
return null;
}
}

Android: drawText not showing up over draw

This is my first Android App and I'm running into some difficulty with drawText(). I have been self-learning Android programming though Mario Zechner's Beginning Android Games. I am adapting the code he uses for the Mr. Nom game in his book to create my own game. This is a color learning game in which the user taps on a grid of colors. I am able to successfully draw the color grid and a space showing the color the user is to "find" using graphics.drawRect(), and a couple of other graphical assets using graphics.drawPixmap(). I am trying to put the name of each color over top of each color filled rectangle. I have thrown in an arbitrary line of text toward the bottom of the code as follows:
p.setTypeface(Typeface.SERIF);
p.setTextSize(100);
p.setColor(Color.WHITE);
p.setStyle(Style.FILL);
canvas.drawPaint(p);
canvas.drawText("RED",120, 120, p);
Reading similar quesitons I believe my issue is that I'm not properly telling it to draw to the same screen as the rest of the graphical elements. I'm sorry if I'm not being clear - again this is my first project. Please let me know what other information you might need in helping me.
Thank you for your time and consideration!
Below is the rest of the java code used:
package com.lilyandrosieshow.colors;
import java.util.List;
import java.util.Random;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Canvas;
import android.graphics.Typeface;
import android.graphics.Paint.Style;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.framework.Input.TouchEvent;
import com.badlogic.androidgames.framework.Screen;
import com.badlogic.androidgames.framework.Sound;
import com.lilyandrosieshow.colors.ColorGrid;
public class GameScreen extends Screen {
Random random = new Random();
World world;
ColorGrid colorGrid = new ColorGrid();
Canvas canvas = new Canvas();
Paint p = new Paint();
static Sound[] colorSoundL = { Assets.lred, Assets.lorange, Assets.lyellow, Assets.lgreen,
Assets.lblue, Assets.lpurple, Assets.lbrown, Assets.lgrey,
Assets.lblack, Assets.lpink, Assets.lcyan, Assets.lwhite };
static Sound[] colorSoundR = { Assets.rred, Assets.rorange, Assets.ryellow, Assets.rgreen,
Assets.rblue, Assets.rpurple, Assets.rbrown, Assets.rgrey,
Assets.rblack, Assets.rpink, Assets.rcyan, Assets.rwhite };
static Sound[] correct1 = { Assets.correct1, Assets.correct2, Assets.correct3, Assets.correct4, Assets.correct5 };
static Sound[] correct2 = { Assets.correcta, Assets.correctb, Assets.correctc, Assets.correctd, Assets.correcte };
static Sound[] wrong1 = {Assets.wrong1, Assets.wrong2, Assets.wrong3, Assets.wrong4, Assets.wrong5 };
static Sound[] wrong2 = {Assets.wronga, Assets.wrongb, Assets.wrongc, Assets.wrongd, Assets.wronge };
static Sound[] ask = {Assets.ask1, Assets.ask2, Assets.ask3, Assets.ask4, Assets.ask5 };
static Sound[] repeat = { Assets.again1, Assets.again2, Assets.again3, Assets.again4, Assets.again5 };
int row = -1;
int column = -1;
public GameScreen(Game game) {
super(game);
this.world = new World();
}
#Override
public void update(float deltaTime) {
List<TouchEvent> touchEvents = game.getInput().getTouchEvents();
int len = touchEvents.size();
for (int i = 0; i < len; i++) {
TouchEvent event = touchEvents.get(i);
// Color Touched
if (event.type == TouchEvent.TOUCH_UP &&
event.x >= 0 && event.x <= 320 && event.y >= 0 && event.y <= 240) {
for (int j = 1; j <= 4; j++){
if (event.x < (j*80)) {
column = j;
break;
}
}
for (int j = 1; j <= 3; j++){
if (event.y < (j*80)) {
row = j;
break;
}
}
updateColorTouched(column, row);
if (world.colorTouched.x == world.colorWanted.x && world.colorTouched.y == world.colorWanted.y) {
correct2[new Random().nextInt(5)].play(1);
if (world.whichHead == World.WhichHead.LILY) colorSoundL[world.colorTouched.id].play(1);
if (world.whichHead == World.WhichHead.ROSIE) colorSoundR[world.colorTouched.id].play(1);
//world.colorTouched.s.play(1);
world.colorWanted = colorGrid.squares.get(random.nextInt(12));
//Assets.ask1.play(1);
//colorSet[colorWanted-1].play(1);
} else {
wrong2[new Random().nextInt(5)].play(1);
//colorSet[colorTouched-1].play(1);
}
}
// A Head Was Touched
if (event.type == TouchEvent.TOUCH_UP && event.y > 240 && event.y <= 480){
if (event.x > 0 && event.x < 160) world.changeVoice(World.WhichHead.LILY);
if (event.x > 161 && event.x < 320) world.changeVoice(World.WhichHead.ROSIE);
}
}
}
#Override
public void present(float deltaTime) { // Draw everything to the screen here
Graphics g = game.getGraphics();
g.drawRect(0, 0, g.getWidth(), g.getHeight(), Color.rgb(75, 75, 75));
g.drawPixmap(Assets.findthis, 5, 245);
g.drawRect(165, 245, 150, 70, Color.rgb(world.colorWanted.r,
world.colorWanted.g,
world.colorWanted.b));
g.drawPixmap(Assets.lilyheadopen, 5, 325, 5, 5, 155, 155);
g.drawPixmap(Assets.rosieheadopen, 165, 325, 5, 5, 155, 155);
// Draws the grid
for (int i = 0; i < 12; i++) {
g.drawRect((
(world.colorGrid.squares.get(i).x-1)*80),
(world.colorGrid.squares.get(i).y-1)*80,
80,
80,
Color.rgb(world.colorGrid.squares.get(i).r, world.colorGrid.squares.get(i).g, world.colorGrid.squares.get(i).b));
// ************* DRAW TEXT NAMES HERE ********************
p.setTypeface(Typeface.SERIF);
p.setTextSize(100);
p.setColor(Color.WHITE);
p.setStyle(Style.FILL);
canvas.drawPaint(p);
canvas.drawText("RED",120, 120, p);
}
}
public void updateColorTouched(int x, int y){
for (int i = 1; i <= 12; i++) {
if (x == world.colorGrid.squares.get(i-1).x && y == world.colorGrid.squares.get(i-1).y){
world.colorTouched = world.colorGrid.squares.get(i-1);
break;
}
}
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void dispose() {
}
}
Rather than drawing to a Canvas object that doesn't get used anywhere, you'll probably want to extend the Graphics interface with a drawText(...) method. This would be analogue to all other draw calls that are defined in Graphics and implemented in AndroidGraphics.
To help you on your way:
Add to Graphics.java:
public void drawText(String text, float x, float y, Paint p);
Add to AndroidGraphics.java:
#Override public void drawText(String text, float x, float y, Paint p) {
paint.set(p);
canvas.drawText(text, x, y, paint);
}
If you need any of the other drawText(...) overloads that are available in Android's Canvas class, you can repeat the same steps as outlined above for those.
try this:
p.setTypeface(Typeface.SERIF);
p.setTextSize(100);
p.setColor(Color.WHITE);
p.setStyle(Style.FILL);
Bitmap bitmap = Bitmap.createBitmap(200,200,Bitmap.Config.ARGB_8888);
canvas = new Canvas(bitmap);
//canvas.drawPaint(p);
canvas.drawText("RED",120, 120, p);
g.drawPixmap(new AndroidPixmap(bitmap,PixmapFormat.ARG_8888),839,282);//your actual
//coordinates instead of 839,282 though

Categories

Resources