Thread troubles and drawing line on view - java

I want to draw a line with this code but on the image view I can't see a picture. If I call only paintComponent() it works very well. I can see two lines but if I call startDrawing(), I get the error below. At first, I tried without new Canvas() and setImageView() but theres nothing to do.
LogCat:
07-21 04:41:43.489: W/System.err(1770): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
07-21 04:41:43.529: W/System.err(1770): at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6094)
07-21 04:41:43.529: W/System.err(1770): at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:857)
07-21 04:41:43.529: W/System.err(1770): at android.view.ViewGroup.invalidateChild(ViewGroup.java:4320)
07-21 04:41:43.549: W/System.err(1770): at android.view.View.invalidate(View.java:10935)
07-21 04:41:43.569: W/System.err(1770): at android.view.View.invalidate(View.java:10890)
07-21 04:41:43.569: W/System.err(1770): at android.widget.ImageView.setImageDrawable(ImageView.java:426)
07-21 04:41:43.569: W/System.err(1770): at android.widget.ImageView.setImageBitmap(ImageView.java:439)
07-21 04:41:43.569: W/System.err(1770): at graphing.GraphPanel.run(GraphPanel.java:577)
07-21 04:41:43.569: W/System.err(1770): at java.lang.Thread.run(Thread.java:841)*
There is code:
public class GraphPanel implements Runnable {
private static final long serialVersionUID = -8880798842884968375L;
private double minX = -10;
private double maxX = 10;
private double minY = -10;
private double maxY = 10;
private double xInterval;
private double yInterval;
private int xAxis = 0;
private int yAxis = 0;
private int panelHeight = 0;
private int panelWidth = 0;
private boolean firstResize = true;
private static Vector<Equation> equations = new Vector<Equation>();
private static Vector<Path> polylines = new Vector<Path>();
private Vector<Thread> threads = new Vector<Thread>();
private boolean stopThreads = false;
private boolean painting = false;
private int currentEq = 0;
private static HashMap<String, PointF> points = new HashMap<String, PointF>();
SurfaceView view;
private Canvas g2;
private Paint p;
ImageView imageview;
Bitmap bitmap;
public GraphPanel(ImageView imageview, int width, int height) {
bitmap = Bitmap.createBitmap( width,height, Bitmap.Config.ARGB_8888);
p=new Paint();
p.setColor(Color.GREEN);
// TODO Auto-generated constructor stub
this.imageview=imageview;
}
private void init() {
// TODO Auto-generated method stub
}
public void paintComponent() {
painting = true;
g2 = new Canvas(bitmap);
imageview.setImageBitmap(bitmap);
p.setColor(Color.GREEN);
yAxis = UnitToPixelX(0);
xAxis = UnitToPixelY(0);
// GraphSettings.setDrawGrid(true);
// Draw Grid
if (GraphSettings.isDrawGrid()) {
//g2.setColor(Color.GRAY);
xInterval = Math.pow(10, String.valueOf((int) (maxX - minX) / 4).length() - 1);
yInterval = Math.pow(10, String.valueOf((int) (maxY - minY) / 4).length() - 1);
xInterval = yInterval = Math.min(xInterval, yInterval);
for (double i = 0 + xInterval; i <= maxX; i += xInterval) {
g2.drawLine(UnitToPixelX(i), 0, UnitToPixelX(i), g2.getHeight(),p);
}
for (double i = 0 - xInterval; i >= minX; i -= xInterval) {
g2.drawLine(UnitToPixelX(i), 0, UnitToPixelX(i), g2.getHeight(),p);
}
for (double i = 0 + yInterval; i <= maxY; i += yInterval) {
g2.drawLine(0, UnitToPixelY(i), g2.getWidth(), UnitToPixelY(i),p);
}
for (double i = 0 - yInterval; i >= minY; i -= yInterval) {
g2.drawLine(0, UnitToPixelY(i), g2.getWidth(), UnitToPixelY(i),p);
}
}
// Draw crossheir
g2.drawLine(g2.getWidth() / 2 - 5, g2.getHeight() / 2, g2.getWidth() / 2 + 5, g2.getHeight() / 2,p);
g2.drawLine(g2.getWidth() / 2, g2.getHeight() / 2 - 5, g2.getWidth() / 2, g2.getHeight() / 2 + 5,p);
// Draw x and y axis
g2.drawLine(0, xAxis, g2.getWidth(), xAxis,p);
g2.drawLine(yAxis, 0, yAxis, g2.getHeight(),p);
painting=false;
}
private synchronized void increasePolylineNumber(int eqNumber) {
while (polylines.size() < eqNumber + 1) {
polylines.add(new Path());
}
}
public void startDrawing() {
stopThreads = true;
for (Thread t : threads) {
t.stop(); //TODO: Terbile design. This should be changed later. But it works for testing.
}
threads.clear();
polylines.clear();
stopThreads = false;
// .draw(g2);
// repaint();
for (int i=0; i<equations.size(); i++) {
threads.add(new Thread(this));
threads.lastElement().start();
}
}
#Override
public void run() {
try {
g2=new Canvas(bitmap);
imageview.setImageBitmap(bitmap);
// imageview.setI
int eqNumber = this.getNextEQ();
Equation eq = equations.get(eqNumber);
increasePolylineNumber(eqNumber);
Path polyline = new Path();/*(GeneralPath.WIND_EVEN_ODD, this.getWidth());*/
boolean firstPoint = true;
double interval, intervalFormula, slope;
Double eqVal;
Double eqPrev = 0.0;
String expr = eq.getExpression();
// Set values for loop.
try {
eqPrev = Equation.evaluate(expr, minX, false);
} catch (Exception exc) {
equations.clear();
//JOptionPane.showMessageDialog(this, "Invalid Argument.", "Error", JOptionPane.ERROR_MESSAGE);
return;
}
int unittopixelxmin=UnitToPixelX(minX),
unittopixelxeqprev= UnitToPixelY(eqPrev);
polyline.moveTo(unittopixelxmin,unittopixelxeqprev);
// Printer.print("\neqNumber:" + eqNumber);
// Printer.print("Size:" + polylines.size());
polylines.set(eqNumber, polyline);
interval = intervalFormula = (maxX - minX) / (bitmap.getWidth());
int xtest=0,ytest=0;
// Start loop.
int loop = 0;
for (double x = minX;; x += interval) {
if (stopThreads) {
break;
}
// eqVal and pixValX are used a lot. Solve only once.
eqVal = Equation.evaluate(expr, x, false);
int pixValX = UnitToPixelX(x);
if (eqVal.isNaN() || eqVal.isInfinite()) {
firstPoint = true;
} else if (firstPoint) {
polyline.moveTo(pixValX, UnitToPixelY(eqVal));
polylines.set(eqNumber, polyline);
xtest=pixValX;
ytest=UnitToPixelY(eqVal);
firstPoint = false;
} else {
polyline.lineTo(pixValX, UnitToPixelY(eqVal));
polylines.set(eqNumber, polyline);
xtest=pixValX;
ytest=UnitToPixelY(eqVal);
}
// Set interval.
slope = Math.abs((eqVal - eqPrev) / (x - (x - interval)));
if (slope > GraphSettings.getMinCalcPerPixel()) {
if (slope > GraphSettings.getMaxCalcPerPixel()) {
slope = GraphSettings.getMaxCalcPerPixel();
}
interval = intervalFormula / slope;
} else {
interval = intervalFormula;
}
eqPrev = eqVal;
if ((loop++ % 10 == 0 || x >= maxX) && !painting) {
p.setColor(Color.RED);
g2.drawLine(0,0,120,120, p);
// repaint();
//g2.drawPath(polyline, p);
// view.draw(g2);
}
if (x >= maxX) {
break;
}
}
p.setColor(Color.RED);
g2.drawLine(0,0,120,120, p);
p.setColor(Color.RED);
g2.drawLine(unittopixelxmin,unittopixelxeqprev, xtest, ytest, p);
System.out.print(polylines);
System.out.print(polyline);
// imageview.setImageBitmap(bitmap);
/* for(Path path:polylines){
Log.e(path.toString(), path.toString()) ;
g2.drawPath(path, p);
}*/
} catch (Exception e) {
//JOptionPane.showMessageDialog(this, e, "Error", JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}

Related

How change shape and size of custom drawn shader in glsurface view by getting coordinates from view class

In my application i'm having a custom graph like view firstly beneath the overlaying graph view there is a custom cameraview which extends glsurfaceview here inside camera view class i'm applying live blur filter to camera of device without any problems but however i want to change the shape and size of blur as per the coordinate of my overlay grap view here i'm attaching screenshots of my application:
Below Is the screenshot of what i'm trying to achieve:
Below Is Screenshot of What i'm actaully getting:
Here's my overlaying view class:
public class OverlayView2 extends View {
MainActivity f2396a;
double f2397b;
double f2398c;
double f2399d;
double f2400e;
double f2401f;
int f2402g = 1;
C0905a[] f2403h = {new C0905a(), new C0905a(), new C0905a(), new C0905a(), new C0905a()};
Paint f2404i = new Paint();
double f2405j = 1.0d;
double f2406k;
double f2407l;
double f2408m;
class C0905a {
double f2409a;
double f2410b;
int f2411c = -1;
double f2412d;
double f2413e;
C0905a() {
}
}
public OverlayView2(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
mo3504a();
if (!isInEditMode() && (context instanceof MainActivity)) {
this.f2396a = (MainActivity) context;
}
}
public static float m4357a(Context context, float f) {
return TypedValue.applyDimension(1, f, context.getResources().getDisplayMetrics());
}
public void mo3504a() {
this.f2397b = 0.0d;
this.f2398c = 0.0d;
this.f2399d = 0.0d;
this.f2400e = 0.4d;
this.f2401f = 0.25d;
invalidate();
}
public void mo3505a(double d, double d2, double d3, double d4, Canvas canvas) {
double width = (double) ((getWidth() + getHeight()) * 2);
canvas.drawLine((float) (d - (d3 * width)), (float) (d2 - (d4 * width)), (float) ((d3 * width) + d), (float) ((width * d4) + d2), this.f2404i);
}
public void mo3506a(double d, double d2, Canvas canvas) {
canvas.drawOval(new RectF((float) (0.0d - d), (float) (0.0d - d2), (float) (0.0d + d), (float) (0.0d + d2)), this.f2404i);
}
/* access modifiers changed from: 0000 */
/* renamed from: b */
public void mo3507b() {
double scale = getScale();
double width = (((double) getWidth()) * 0.5d) + (this.f2397b * scale);
double height = (((double) getHeight()) * 0.5d) + (this.f2398c * scale);
double cos = Math.cos(Math.toRadians(this.f2399d)) * this.f2400e * scale;
double sin = Math.sin(Math.toRadians(this.f2399d)) * this.f2400e * scale;
double d = (-Math.sin(Math.toRadians(this.f2399d))) * this.f2401f * scale;
double cos2 = Math.cos(Math.toRadians(this.f2399d)) * this.f2401f * scale;
this.f2403h[0].f2409a = width;
this.f2403h[0].f2410b = height;
this.f2403h[1].f2409a = width - cos;
this.f2403h[1].f2410b = height - sin;
this.f2403h[2].f2409a = cos + width;
this.f2403h[2].f2410b = sin + height;
this.f2403h[3].f2409a = width - d;
this.f2403h[3].f2410b = height - cos2;
this.f2403h[4].f2409a = width + d;
this.f2403h[4].f2410b = height + cos2;
Matrix matrix = new Matrix();
matrix.postScale((float) (this.f2400e * scale), (float) (this.f2401f * scale));
matrix.postRotate((float) this.f2399d);
matrix.postTranslate(((float) getWidth()) * 0.5f, ((float) getHeight()) * 0.5f);
matrix.postTranslate((float) (this.f2397b * scale), (float) (scale * this.f2398c));
matrix.postScale(1.0f / ((float) getWidth()), -1.0f / ((float) getHeight()));
matrix.postTranslate(0.0f, 1.0f);
matrix.invert(matrix);
if (this.f2396a != null && this.f2396a.cameraView != null) {
/* matrix.getValues(this.f2396a.cameraView.f2132f);*/
}
}
public void mo3508c() {
double d;
double scale = getScale();
C0905a aVar = this.f2403h[0];
if (aVar.f2411c >= 0) {
this.f2397b = (aVar.f2409a - (((double) getWidth()) * 0.5d)) / scale;
this.f2398c = (aVar.f2410b - (((double) getHeight()) * 0.5d)) / scale;
}
double d2 = 0.0d;
int i = 0;
double d3 = 0.0d;
double d4 = 0.0d;
int i2 = 0;
int i3 = 0;
for (int i4 = 1; i4 < this.f2403h.length; i4++) {
C0905a aVar2 = this.f2403h[i4];
if (aVar2.f2411c >= 0) {
if (i4 == 1) {
d2 += Math.toDegrees(Math.atan2(-(aVar2.f2410b - this.f2403h[0].f2410b), -(aVar2.f2409a - this.f2403h[0].f2409a)));
i++;
}
if (i4 == 2) {
d2 += Math.toDegrees(Math.atan2(aVar2.f2410b - this.f2403h[0].f2410b, aVar2.f2409a - this.f2403h[0].f2409a));
i++;
}
if (this.f2402g != 1) {
if (i4 == 3) {
d2 += Math.toDegrees(Math.atan2(aVar2.f2409a - this.f2403h[0].f2409a, -(aVar2.f2410b - this.f2403h[0].f2410b)));
i++;
}
if (i4 == 4) {
d2 += Math.toDegrees(Math.atan2(-(aVar2.f2409a - this.f2403h[0].f2409a), aVar2.f2410b - this.f2403h[0].f2410b));
i++;
}
}
double d5 = (this.f2403h[0].f2409a - aVar2.f2409a) / scale;
double d6 = (this.f2403h[0].f2410b - aVar2.f2410b) / scale;
if (i4 == 1 || i4 == 2) {
double cos = (Math.cos(Math.toRadians(this.f2399d)) * d5) + (Math.sin(Math.toRadians(this.f2399d)) * d6);
if (i4 == 2) {
cos = -cos;
}
d = Math.max(0.0d, cos) + d3;
i2++;
} else {
d = d3;
}
if (i4 == 3 || i4 == 4) {
double cos2 = ((-Math.sin(Math.toRadians(this.f2399d))) * d5) + (d6 * Math.cos(Math.toRadians(this.f2399d)));
if (i4 == 4) {
cos2 = -cos2;
}
d4 += Math.max(0.0d, cos2);
i3++;
d3 = d;
} else {
d3 = d;
}
}
}
if (i > 0) {
this.f2399d = d2 / ((double) i);
}
if (i2 > 0) {
this.f2400e = d3 / ((double) i2);
}
if (i3 > 0) {
this.f2401f = d4 / ((double) i3);
}
if (this.f2397b < -0.8d) {
this.f2397b = -0.8d;
}
if (this.f2398c < -0.8d) {
this.f2398c = -0.8d;
}
if (this.f2397b > 0.8d) {
this.f2397b = 0.8d;
}
if (this.f2398c > 0.8d) {
this.f2398c = 0.8d;
}
if (this.f2400e < 0.05d) {
this.f2400e = 0.05d;
}
if (this.f2401f < 0.05d) {
this.f2401f = 0.05d;
}
if (this.f2400e > 1.0d) {
this.f2400e = 1.0d;
}
if (this.f2401f > 1.0d) {
this.f2401f = 1.0d;
}
}
public double getHandleRadius() {
return (double) m4357a(getContext(), 16.0f);
}
public double getScale() {
return (double) (((float) (getWidth() + getHeight())) * 0.5f);
}
public void onDraw(Canvas canvas) {
if (this.f2402g != 0) {
this.f2404i.setColor(-1140850689);
this.f2404i.setStrokeWidth(m4357a(getContext(), 1.5f));
this.f2404i.setStyle(Style.STROKE);
this.f2404i.setAntiAlias(true);
canvas.save();
double scale = getScale();
canvas.translate(((float) getWidth()) * 0.5f, ((float) getHeight()) * 0.5f);
canvas.translate((float) (this.f2397b * scale), (float) (this.f2398c * scale));
canvas.rotate((float) this.f2399d);
mo3505a(0.0d, 0.0d, 1.0d, 0.0d, canvas);
if (this.f2402g == 1) {
mo3505a(0.0d, (this.f2401f * scale) + 0.0d, 1.0d, 0.0d, canvas);
mo3505a(0.0d, 0.0d - (this.f2401f * scale), 1.0d, 0.0d, canvas);
}
mo3505a(0.0d, 0.0d, 0.0d, 1.0d, canvas);
if (this.f2402g == 2) {
mo3506a(this.f2400e * scale, this.f2401f * scale, canvas);
}
canvas.restore();
mo3507b();
double handleRadius = getHandleRadius();
for (int i = 0; i < this.f2403h.length; i++) {
canvas.drawCircle((float) this.f2403h[i].f2409a, (float) this.f2403h[i].f2410b, (float) (this.f2403h[i].f2411c >= 0 ? 1.25d * handleRadius : handleRadius), this.f2404i);
}
}
}
public boolean onTouchEvent(MotionEvent motionEvent) {
boolean z;
C0905a[] aVarArr;
C0905a[] aVarArr2;
if (this.f2402g == 0) {
for (C0905a aVar : this.f2403h) {
aVar.f2411c = -1;
}
return super.onTouchEvent(motionEvent);
}
boolean z2 = false;
int actionMasked = motionEvent.getActionMasked();
if (actionMasked == 0 || actionMasked == 5) {
z2 = true;
double d = Double.MAX_VALUE;
C0905a aVar2 = null;
int actionIndex = motionEvent.getActionIndex();
int pointerId = motionEvent.getPointerId(actionIndex);
double x = (double) motionEvent.getX(actionIndex);
double y = (double) motionEvent.getY(actionIndex);
double handleRadius = getHandleRadius() * 2.5d;
double d2 = handleRadius * handleRadius;
C0905a[] aVarArr3 = this.f2403h;
int length = aVarArr3.length;
int i = 0;
while (i < length) {
C0905a aVar3 = aVarArr3[i];
double d3 = aVar3.f2409a - x;
double d4 = aVar3.f2410b - y;
double d5 = (d3 * d3) + (d4 * d4);
if (d5 >= d2 || d5 >= d) {
aVar3 = aVar2;
d5 = d;
}
i++;
d = d5;
aVar2 = aVar3;
}
if (aVar2 != null) {
aVar2.f2411c = pointerId;
aVar2.f2412d = x - aVar2.f2409a;
aVar2.f2413e = y - aVar2.f2410b;
}
}
if (actionMasked == 5) {
for (C0905a aVar4 : this.f2403h) {
aVar4.f2411c = -1;
}
}
if ((actionMasked == 2 || actionMasked == 5) && motionEvent.getPointerCount() == 2) {
double x2 = (double) (motionEvent.getX(0) - motionEvent.getX(1));
double y2 = (double) (motionEvent.getY(0) - motionEvent.getY(1));
double sqrt = Math.sqrt((x2 * x2) + (y2 * y2));
double degrees = Math.toDegrees(Math.atan2((double) (motionEvent.getY(0) - motionEvent.getY(1)), (double) (motionEvent.getX(0) - motionEvent.getX(1))));
if (actionMasked == 2) {
double d6 = sqrt / this.f2405j;
this.f2400e *= d6;
this.f2401f = d6 * this.f2401f;
this.f2399d += degrees - this.f2408m;
}
this.f2405j = sqrt;
this.f2408m = degrees;
}
if (actionMasked == 2 || actionMasked == 5 || actionMasked == 0 || actionMasked == 1 || actionMasked == 6) {
double d7 = 0.0d;
double d8 = 0.0d;
int i2 = 0;
for (int i3 = 0; i3 < motionEvent.getPointerCount(); i3++) {
if (actionMasked != 6 || i3 != motionEvent.getActionIndex()) {
d7 += (double) motionEvent.getX(i3);
d8 += (double) motionEvent.getY(i3);
i2++;
}
}
if (i2 > 0) {
double d9 = d7 / ((double) i2);
double d10 = d8 / ((double) i2);
if (actionMasked == 2) {
boolean z3 = true;
for (C0905a aVar5 : this.f2403h) {
if (aVar5.f2411c >= 0) {
z3 = false;
}
}
if (z3) {
double scale = 1.0d / getScale();
this.f2397b += (d9 - this.f2406k) * scale;
this.f2398c = (scale * (d10 - this.f2407l)) + this.f2398c;
}
}
this.f2406k = d9;
this.f2407l = d10;
}
}
if (actionMasked == 2) {
z = true;
int pointerCount = motionEvent.getPointerCount();
for (int i4 = 0; i4 < pointerCount; i4++) {
int pointerId2 = motionEvent.getPointerId(i4);
double x3 = (double) motionEvent.getX(i4);
double y3 = (double) motionEvent.getY(i4);
for (C0905a aVar6 : this.f2403h) {
if (aVar6.f2411c == pointerId2) {
aVar6.f2409a = x3 - aVar6.f2412d;
aVar6.f2410b = y3 - aVar6.f2413e;
}
}
}
} else {
z = z2;
}
if (actionMasked == 1 || actionMasked == 6) {
z = true;
int pointerId3 = motionEvent.getPointerId(motionEvent.getActionIndex());
for (C0905a aVar7 : this.f2403h) {
if (aVar7.f2411c == pointerId3) {
aVar7.f2411c = -1;
}
}
}
if (actionMasked == 3) {
z = true;
for (C0905a aVar8 : this.f2403h) {
aVar8.f2411c = -1;
}
}
if (z) {
mo3508c();
invalidate();
if (this.f2396a != null) {
this.f2396a.cameraView.requestRender();
}
}
return super.onTouchEvent(motionEvent) || z;
}
}
Here's my cameraview class:
public class CameraView extends GLSurfaceView implements Renderer {
public static long maxsize = 1280;
final String TAG = "CameraView";
public Bitmap bitmap = null;
public Bitmap bitmap0 = null;
int bitmaptexture = -1;
boolean bresize = true;
public float f0c;
public static Camera camera;
SurfaceTexture cameraSurface;
int cameraTexture;
boolean created = false;
boolean doloadbitmap = false;
public boolean isFrontFacing;
Framebuffer fa;
Framebuffer fb;
/* renamed from: h */
int f1h;
public static int ak;
OnPhotoListener photoListener;
Quad quad = new Quad();
public float f2r;
public float f3s;
Shader shblur;
Shader shconv;
Shader shcopy;
Shader shfina;
Shader shflip;
int f4w;
public float f5y;
public interface OnPhotoListener {
void onPhoto(Bitmap bitmap);
}
public void takePhoto(OnPhotoListener l) {
this.photoListener = l;
requestRender();
}
static Bitmap takeScreenshot(int x, int y, int w, int h) {
int[] b = new int[((y + h) * w)];
int[] bt = new int[(w * h)];
IntBuffer ib = IntBuffer.wrap(b);
ib.position(0);
GLES20.glReadPixels(x, 0, w, y + h, 6408, 5121, ib);
int i = 0;
int k = 0;
while (i < h) {
for (int j = 0; j < w; j++) {
int pix = b[(i * w) + j];
bt[(((h - k) - 1) * w) + j] = ((-16711936 & pix) | ((pix << 16) & 16711680)) | ((pix >> 16) & MotionEventCompat.ACTION_MASK);
}
i++;
k++;
}
return Bitmap.createBitmap(bt, w, h, Config.ARGB_8888);
}
public CameraView(Context context, AttributeSet attrs) {
super(context, attrs);
setEGLContextClientVersion(2);
setRenderer(this);
setRenderMode(0);
requestRender();
}
void m7x(Framebuffer src, Framebuffer dst, float dx, float dy) {
dst.bind(this.f4w, this.f1h);
this.shblur.use();
this.shblur.tex("s", src.tex());
this.shblur.set("o", (double) dx, (double) dy);
this.shblur.set("y", (double) this.f5y);
this.shblur.set("z", (double) this.f3s);
this.quad.draw();
}
void m6x() {
float radius = this.f2r;
float rx = ((radius / 8.0f) / ((float) this.f4w)) * ((float) this.f1h);
float ry = radius / 8.0f;
m7x(this.fa, this.fb, rx / 8.0f, 0.0f);
m7x(this.fb, this.fa, rx / 1.0f, 0.0f);
m7x(this.fa, this.fb, 0.0f, ry / 8.0f);
m7x(this.fb, this.fa, 0.0f, ry / 1.0f);
m7x(this.fa, this.fb, rx / 8.0f, 0.0f);
m7x(this.fb, this.fa, rx / 1.0f, 0.0f);
m7x(this.fa, this.fb, 0.0f, ry / 8.0f);
m7x(this.fb, this.fa, 0.0f, ry / 1.0f);
}
public void onDrawFrame(GL10 _gl) {
GLES20.glClear(16384);
GLES20.glDisable(2929);
GLES20.glDisable(2884);
GLES20.glDisable(3042);
GLES20.glEnableVertexAttribArray(0);
Bitmap b = this.bitmap;
if (b != null) {
this.f4w = b.getWidth();
this.f1h = b.getHeight();
if (this.doloadbitmap) {
loadbitmap();
this.doloadbitmap = false;
}
this.fa.bind(this.f4w, this.f1h);
this.shflip.use();
this.shflip.tex("s", this.bitmaptexture);
this.quad.draw();
} else if (this.camera != null && this.cameraSurface != null) {
Size cameraSize = null;
try {
this.camera.setPreviewTexture(this.cameraSurface);
this.cameraSurface.updateTexImage();
cameraSize = this.camera.getParameters().getPreviewSize();
} catch (Exception e) {
e.printStackTrace();
}
if (this.camera != null && cameraSize != null && this.cameraSurface != null) {
this.f4w = cameraSize.width;
this.f1h = cameraSize.height;
this.fa.bind(this.f4w, this.f1h);
this.shconv.use();
this.shconv.tex("s", this.cameraTexture, 0, 36197);
this.quad.draw();
} else {
return;
}
} else {
return;
}
m6x();
this.fb.bind(this.fa.f7w, this.fa.f6h);
this.shfina.use();
this.shfina.tex("s", this.fa.tex());
this.shfina.set("c", (double) this.f0c);
this.quad.draw();
OnPhotoListener l = this.photoListener;
this.photoListener = null;
if (l != null) {
Bitmap bmp = takeScreenshot(0, 0, this.f4w, this.f1h);
l.onPhoto(bmp);
bmp.recycle();
requestRender();
}
Framebuffer.reset(getWidth(), getHeight());
GLES20.glClear(16384);
if ((((double) this.f4w) * 1.0d) / ((double) this.f1h) > (((double) getWidth()) * 1.0d) / ((double) getHeight())) {
int h2 = (getWidth() * this.f1h) / this.f4w;
GLES20.glViewport(0, (getHeight() - h2) / 2, getWidth(), h2);
} else {
int w2 = (getHeight() * this.f4w) / this.f1h;
GLES20.glViewport((getWidth() - w2) / 2, 0, w2, getHeight());
}
this.shcopy.use();
this.shcopy.tex("s", this.fb.tex());
this.quad.draw();
}
public void onSurfaceChanged(GL10 _gl, int width, int height) {
}
int genTexture() {
int[] tt = new int[1];
GLES20.glGenTextures(1, tt, 0);
return tt[0];
}
public void onSurfaceCreated(GL10 _gl, EGLConfig config) {
this.fa = new Framebuffer();
this.fb = new Framebuffer();
this.shconv = new Shader(getContext(), R.raw.flip, R.raw.conv);
this.shflip = new Shader(getContext(), R.raw.flip, R.raw.copy);
this.shblur = new Shader(getContext(), R.raw.btex, R.raw.blur);
this.shfina = new Shader(getContext(), R.raw.quad, R.raw.fina);
this.shcopy = new Shader(getContext(), R.raw.quad, R.raw.copy);
this.cameraTexture = genTexture();
this.cameraSurface = new SurfaceTexture(this.cameraTexture);
this.bitmaptexture = genTexture();
this.created = true;
this.doloadbitmap = true;
}
public void createCamera(int mReqCameraId) {
Log.i(TAG, "createCamera");
requestRender();
if (this.camera == null) {
try {
if (mReqCameraId == Camera.CameraInfo.CAMERA_FACING_BACK) {
isFrontFacing = false;
} else {
isFrontFacing = true;
}
this.camera = Camera.open(mReqCameraId);
/*if(Share.back_camera){
this.camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
}else{
this.camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
}*/
Parameters params = this.camera.getParameters();
params.setRecordingHint(true);
if (params.getSupportedFocusModes().contains("continuous-picture")) {
params.setFocusMode("continuous-picture");
}
Size best = null;
for (Size s : params.getSupportedPreviewSizes()) {
if (best == null || s.width * s.height < best.width * best.height) {
best = s;
}
}
if (best != null) {
Log.i("Size", best.width + " " + best.height);
params.setPreviewSize(best.width, best.height);
}
this.camera.setParameters(params);
this.camera.startPreview();
setRenderMode(1);
} catch (final Throwable ex) {
((Activity) getContext()).runOnUiThread(new Runnable() {
class C01341 implements OnClickListener {
C01341() {
}
public void onClick(DialogInterface arg0, int arg1) {
CameraView.this.createCamera(0);
}
#Override
public void onClick(View v) {
}
}
/* renamed from: camera.tiltshift.CameraView$1$2 */
class C01352 implements OnClickListener {
C01352() {
}
public void onClick(DialogInterface arg0, int arg1) {
throw new RuntimeException(ex);
}
#Override
public void onClick(View v) {
}
}
public void run() {
}
});
}
}
}
void destroyCamera() {
Log.i("CameraView", "destroyCamera");
if (this.camera != null) {
this.camera.stopPreview();
this.camera.release();
}
this.camera = null;
setRenderMode(0);
requestRender();
}
public void setBitmap(Bitmap b) {
this.bitmap0 = b;
if (b != null && this.bresize && (((long) b.getWidth()) > maxsize || ((long) b.getHeight()) > maxsize)) {
long mx = (long) Math.max(b.getWidth(), b.getHeight());
b = createScaledBitmap2(b, (int) ((((long) b.getWidth()) * maxsize) / mx), (int) ((((long) b.getHeight()) * maxsize) / mx), true);
}
this.bitmap = b;
this.doloadbitmap = true;
requestRender();
}
static Bitmap createScaledBitmap2(Bitmap src, int dstWidth, int dstHeight, boolean filter) {
Log.i("createScaledBitmap2", dstWidth + " " + dstHeight);
Matrix m = new Matrix();
m.setScale(((float) dstWidth) / ((float) src.getWidth()), ((float) dstHeight) / ((float) src.getHeight()));
Bitmap result = Bitmap.createBitmap(dstWidth, dstHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(result);
Paint paint = new Paint();
paint.setFilterBitmap(filter);
canvas.drawBitmap(src, m, paint);
return result;
}
void loadbitmap() {
Bitmap b = this.bitmap;
if (b != null && this.created) {
GLES20.glBindTexture(3553, this.bitmaptexture);
GLES20.glTexParameteri(3553, 10241, 9728);
GLES20.glTexParameteri(3553, 10240, 9728);
GLES20.glTexParameteri(3553, 10242, 33071);
GLES20.glTexParameteri(3553, 10243, 33071);
GLUtils.texImage2D(3553, 0, b, 0);
this.doloadbitmap = false;
}
}
}

draw mandlebrot onto bitmap

I am currently converting java code into c# code and i have it almost working i think but I am trying to draw the mandlebrot onto the bitmap but nothing is displaying . The form pops up but nothing is drawn onto it.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Assignment1
{
public partial class Form1 : Form
{
public Form1()
{
init();
start();
stop();
destroy();
InitializeComponent();
}
public struct HSBColor
{
float h;
float s;
float b;
int a;
public HSBColor(float h, float s, float b)
{
this.a = 0xff;
this.h = Math.Min(Math.Max(h, 0), 255);
this.s = Math.Min(Math.Max(s, 0), 255);
this.b = Math.Min(Math.Max(b, 0), 255);
}
public HSBColor(int a, float h, float s, float b)
{
this.a = a;
this.h = Math.Min(Math.Max(h, 0), 255);
this.s = Math.Min(Math.Max(s, 0), 255);
this.b = Math.Min(Math.Max(b, 0), 255);
}
public float H
{
get { return h; }
}
public float S
{
get { return s; }
}
public float B
{
get { return b; }
}
public int A
{
get { return a; }
}
public Color Color
{
get
{
return FromHSB(this);
}
}
public static Color FromHSB(HSBColor hsbColor)
{
float r = hsbColor.b;
float g = hsbColor.b;
float b = hsbColor.b;
if (hsbColor.s != 0)
{
float max = hsbColor.b;
float dif = hsbColor.b * hsbColor.s / 255f;
float min = hsbColor.b - dif;
float h = hsbColor.h * 360f / 255f;
if (h < 60f)
{
r = max;
g = h * dif / 60f + min;
b = min;
}
else if (h < 120f)
{
r = -(h - 120f) * dif / 60f + min;
g = max;
b = min;
}
else if (h < 180f)
{
r = min;
g = max;
b = (h - 120f) * dif / 60f + min;
}
else if (h < 240f)
{
r = min;
g = -(h - 240f) * dif / 60f + min;
b = max;
}
else if (h < 300f)
{
r = (h - 240f) * dif / 60f + min;
g = min;
b = max;
}
else if (h <= 360f)
{
r = max;
g = min;
b = -(h - 360f) * dif / 60 + min;
}
else
{
r = 0;
g = 0;
b = 0;
}
}
return Color.FromArgb
(
hsbColor.a,
(int)Math.Round(Math.Min(Math.Max(r, 0), 255)),
(int)Math.Round(Math.Min(Math.Max(g, 0), 255)),
(int)Math.Round(Math.Min(Math.Max(b, 0), 255))
);
}
}
private const int MAX = 256; // max iterations
private const double SX = -2.025; // start value real
private const double SY = -1.125; // start value imaginary
private const double EX = 0.6; // end value real
private const double EY = 1.125; // end value imaginary
private static int x1, y1, xs, ys, xe, ye;
private static double xstart, ystart, xende, yende, xzoom, yzoom;
private static bool action, rectangle, finished;
private static float xy;
private Image picture;
private Graphics g1;
private Cursor c1, c2;
//private HSB HSBcol=new HSB();
public void init() // all instances will be prepared
{
//HSBcol = new HSB();
this.Size = new Size(640,480);
finished = false;
//addMouseListener(this);
//addMouseMotionListener(this);
//c1 = new Cursor(Cursor.WAIT_CURSOR);
//c2 = new Cursor(Cursor.CROSSHAIR_CURSOR);
x1 = this.Width;
y1 = this.Height;
xy = (float)x1 / (float)y1;
Bitmap img = new Bitmap(1, 1);
g1 = Graphics.FromImage(img);
finished = true;
}
public void destroy() // delete all instances
{
if (finished)
{
//removeMouseListener(this);
//removeMouseMotionListener(this);
picture = null;
g1 = null;
c1 = null;
c2 = null;
GC.Collect(); // garbage collection
}
}
public void start()
{
action = false;
rectangle = false;
initvalues();
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
}
public void stop()
{
}
public void paint(Graphics g)
{
update(g);
}
public void update(Graphics g)
{
g.DrawImage(picture, 0, 0);
if (rectangle)
{
Pen WhitePen = new Pen(Color.White);
if (xs < xe)
{
if (ys < ye) g.DrawRectangle(WhitePen, xs, ys, (xe - xs), (ye - ys));
else g.DrawRectangle(WhitePen, xs, ye, (xe - xs), (ys - ye));
}
else
{
if (ys < ye) g.DrawRectangle(WhitePen, xe, ys, (xs - xe), (ye - ys));
else g.DrawRectangle(WhitePen, xe, ye, (xs - xe), (ys - ye));
}
}
}
private void mandelbrot() // calculate all points
{
int x, y;
float h, b, alt = 0.0f;
Pen FractalPen;
action = false;
//SetCursor(c1);
//showStatus("Mandelbrot-Set will be produced - please wait...");
for (x = 0; x < x1; x+=2)
for (y = 0; y < y1; y++)
{
h = pointcolour(xstart + xzoom * (double)x, ystart + yzoom * (double)y); // color value
if (h != alt)
{
b = 1.0f - h * h; // brightnes
///djm added
//HSBcol.fromHSB(h,0.8f,b); //convert hsb to rgb then make a Java Color
Color color = HSBColor.FromHSB(new HSBColor(h * 255, 0.8f * 255, b * 255)); // VERY IMPORTANT
//g1.setColor(col);
//djm end
//djm added to convert to RGB from HSB
//g1.setColor(Color.getHSBColor(h, 0.8f, b));
//djm test
//Color col = Color.getHSBColor(h,0.8f,b);
//int red = col.getRed();
//int green = col.getGreen();
//int blue = col.getBlue();
//djm
alt = h;
FractalPen = new Pen(color);
g1.DrawLine(FractalPen, x, y, x + 1, y);
}
}
//showStatus("Mandelbrot-Set ready - please select zoom area with pressed mouse.");
//setCursor(c2);
action = true;
}
private float pointcolour(double xwert, double ywert) // color value from 0.0 to 1.0 by iterations
{
double r = 0.0, i = 0.0, m = 0.0;
int j = 0;
while ((j < MAX) && (m < 4.0))
{
j++;
m = r * r - i * i;
i = 2.0 * r * i + ywert;
r = m + xwert;
}
return (float)j / (float)MAX;
}
private void initvalues() // reset start values
{
xstart = SX;
ystart = SY;
xende = EX;
yende = EY;
if ((float)((xende - xstart) / (yende - ystart)) != xy )
xstart = xende - (yende - ystart) * (double)xy;
}
/*public void mousePressed(MouseEvent e)
{
e.consume();
if (action)
{
xs = e.getX();
ys = e.getY();
}
}
public void mouseReleased(MouseEvent e)
{
int z, w;
e.consume();
if (action)
{
xe = e.getX();
ye = e.getY();
if (xs > xe)
{
z = xs;
xs = xe;
xe = z;
}
if (ys > ye)
{
z = ys;
ys = ye;
ye = z;
}
w = (xe - xs);
z = (ye - ys);
if ((w < 2) && (z < 2)) initvalues();
else
{
if (((float)w > (float)z * xy)) ye = (int)((float)ys + (float)w / xy);
else xe = (int)((float)xs + (float)z * xy);
xende = xstart + xzoom * (double)xe;
yende = ystart + yzoom * (double)ye;
xstart += xzoom * (double)xs;
ystart += yzoom * (double)ys;
}
xzoom = (xende - xstart) / (double)x1;
yzoom = (yende - ystart) / (double)y1;
mandelbrot();
rectangle = false;
repaint();
}
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseDragged(MouseEvent e)
{
e.consume();
if (action)
{
xe = e.getX();
ye = e.getY();
rectangle = true;
repaint();
}
}
public void mouseMoved(MouseEvent e)
{
}
public String getAppletInfo()
{
return "fractal.class - Mandelbrot Set a Java Applet by Eckhard Roessel 2000-2001";
}*/
}
}
Bitmap img = new Bitmap(1, 1);
This could be the problem. You forgot to replace it with width,height. Like this
Bitmap img = new Bitmap(x1, y1);
call your paint method like this (picturebox is not needed, but for me it was fastest when painting with winforms:
Rectangle r = new Rectangle();
var g = pictureBox1.CreateGraphics();
var pea = new PaintEventArgs(g, r);
yourPaintMethod(pea);
calls:
public void yourPaintMethod(PaintEventArgs e ) {
Graphics g = e.Graphics;
Pen pBlack = new Pen(Color.Black, 1);
g.DrawLine(pBlack........ etc.

How to insert a button using Java Based Program in Eclipse

I just want to ask how to create a button using java based program. I want to have a button on my official game like Next button that if the user clicked it, it will allow them to go to the next level of the game. It's like a pause/resume/stop/restart button inside the game.
This is the code of the Game I used. I can't see the declaration of button here but when I played this, it has a exit button(?) above that allows the user to go back to previous form.
public class NewGame extends Activity {
static MediaPlayer mp1;
MediaPlayer jump;
MediaPlayer takecoin;
GameLoopThread gameLoopThread;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for no title
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(new GameView(this));
}
public class GameView extends SurfaceView {
Bitmap bmp;
Bitmap background, taya, note1;
Bitmap run1;
Bitmap run6;
Bitmap jump2;
Bitmap coin;
Bitmap exit;
// MediaPlayer mp1,jump,takecoin;
private SurfaceHolder holder;
// private gameloop gameLoopThread;
private int x = 0, y = 0, z = 0, delay = 0, getx, gety, sound = 1;
int show = 0, sx, sy = 0;
int cspeed = 0, kspeed = 0, gameover = 0;
int score = 0, health = 120, reset = 0;
private int min = 1, sec = 0;
private Handler mHandler = new Handler();
private Runnable mRunnable;
private boolean isStop = false;
#SuppressWarnings("deprecation")
#SuppressLint("NewApi")
public GameView(Context context) {
super(context);
mHandler.postDelayed(mRunnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if(sec <= 0){
if(min > 0){
sec = 59;
min--;
isStop = false;
}
else{
//stop timer here
Log.e("TIMER", "timer stop!");
mHandler.removeCallbacks(this);
isStop = true;
}
}
else{
sec--;
isStop = false;
}
Log.i("TIMER", "min: " + min + " sec: " + sec);
if(!isStop){
mHandler.postDelayed(this, 1000);
}
}
}, 1000);
gameLoopThread = new GameLoopThread(this);
holder = getHolder();
holder.addCallback(new SurfaceHolder.Callback() {
#SuppressWarnings("deprecation")
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// for stoping the game
gameLoopThread.setRunning(false);
gameLoopThread.getThreadGroup().interrupt();
}
#SuppressLint("WrongCall")
#Override
public void surfaceCreated(SurfaceHolder holder) {
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
// getting the screen size
Display display = getWindowManager().getDefaultDisplay();
sx = display.getWidth();
sy = display.getHeight();
;
cspeed = x / 4;
kspeed = x / 4;
background = BitmapFactory.decodeResource(getResources(),
R.drawable.imgluneta);
run1 = BitmapFactory
.decodeResource(getResources(), R.drawable.run1);
run6 = BitmapFactory
.decodeResource(getResources(), R.drawable.run6);
jump2 = BitmapFactory.decodeResource(getResources(),
R.drawable.run11);
coin = BitmapFactory
.decodeResource(getResources(), R.drawable.coin);
exit = BitmapFactory
.decodeResource(getResources(), R.drawable.exit);
taya = BitmapFactory
.decodeResource(getResources(), R.drawable.taya);
note1 = BitmapFactory.decodeResource(getResources(),
R.drawable.note1);
exit = Bitmap.createScaledBitmap(exit, 25, 25, true);
background = Bitmap
.createScaledBitmap(background, 2 * sx, sy, true);
// health dec
note1 = Bitmap.createScaledBitmap(note1, sx, sy, true);
mp1 = MediaPlayer.create(NewGame.this, R.raw.game);
jump = MediaPlayer.create(NewGame.this, R.raw.jump);
takecoin = MediaPlayer.create(NewGame.this, R.raw.cointake);
}
// on touch method
#Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
show = 1;
getx = (int) event.getX();
gety = (int) event.getY();
// exit
if (getx < 25 && gety < 25) {
System.exit(0);
}
// sound off
if (getx > 25 && getx < 60) {
if (gety < 25) {
sound = 0;
mp1.stop();
}
}
// sound on
if (getx > 61 && getx < 90) {
if (gety < 25) {
sound = 1;
}
}
// restart game
if (getx > 91 && gety < 25) {
if (health <= 0) {
gameLoopThread.setPause(0);
health = 100;
score = 0;
}
}
}
return true;
}
#SuppressLint("WrongCall")
#Override
public void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
// background moving
z = z - 10;
if (z == -sx) {
z = 0;
canvas.drawBitmap(background, z, 0, null);
} else {
canvas.drawBitmap(background, z, 0, null);
}
// running player
x += 5;
if (x == 20) {
x = 5;
}
if (show == 0) {
if (x % 2 == 0) {
int height = run1.getHeight();
canvas.drawBitmap(run1, sx / 16, (15 * sy / 18) - height / 2, null);
// kinfe hit
if (kspeed == 20) {
kspeed = sx;
health -= 25;
canvas.drawBitmap(note1, 0, 0, null);
}
} else {
int height = run6.getHeight();
canvas.drawBitmap(run6, sx / 16, (15 * sy / 18) - height / 2, null);
// kinfe hit
if (kspeed == 20) {
kspeed = sx / 2;
health -= 25;
canvas.drawBitmap(note1, 0, 0, null);
}
}
}
// for jump
if (show == 1) {
if (sound == 1) {
jump.start();
}
int height=jump2.getHeight();
canvas.drawBitmap(jump2, sx / 16, (3 * sy / 4)-height, null);
// score
if (cspeed <= (sx / 8)-height/2 && cspeed >= (sx / 16)-height/2) {
if (sound == 1) {
takecoin.start();
}
cspeed = sx / 2;
score += 10;
}
// jump-hold
delay += 1;
if (delay == 3) {
show = 0;
delay = 0;
}
}
// for coins
cspeed = cspeed - 5;
if (cspeed == -sx / 2) {
cspeed = sx / 2;
canvas.drawBitmap(coin, cspeed, 3 * sy / 4, null);
} else {
canvas.drawBitmap(coin, cspeed, 3 * sy / 4, null);
}
// kinfe
kspeed = kspeed - 20;
int height = taya.getHeight();
canvas.drawBitmap(taya, kspeed, (15 * sy / 18) - height / 2, null);
if (kspeed < 0) {
kspeed = sx;
health -= 25;
}
// score
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setAntiAlias(true);
paint.setFakeBoldText(true);
paint.setTextSize(15);
paint.setTextAlign(Align.LEFT);
canvas.drawText("Score :" + score, 3 * sx / 4, 20, paint);
// exit
canvas.drawBitmap(exit, 0, 0, null);
if (sound == 1) {
mp1.start();
mp1.setLooping(true);
}
// health
Paint myPaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(10);
canvas.drawText("Health :" + health, 0, (sy / 8) - 5, myPaint);
canvas.drawRect(0, sy / 8, health, sy / 8 + 10, myPaint);
// game over
if (health <= 0) {
gameover = 1;
mp1.stop();
canvas.drawText("GAMEOVER OVER", sx / 2, sy / 2, myPaint);
canvas.drawText("YOUR SCORE : " + score, sx / 2, sy / 4,
myPaint);
canvas.drawText("Restart", 91, 25, myPaint);
gameLoopThread.setPause(1);
}
// restart
if (reset == 1) {
gameLoopThread.setPause(0);
health = 100;
score = 0;
}
// timer
Paint mypaint = new Paint();
myPaint.setColor(Color.RED);
myPaint.setStrokeWidth(10);
mypaint.setTextSize(50);
canvas.drawText("Timer :" + min + sec,min, sec, mypaint);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onResume() {
super.onResume();
NewGame.mp1.isPlaying();
}
#Override
public void onPause() {
super.onPause();
NewGame.mp1.pause();
}
}
You can create a button in Java code-
Button button = new Button(this);
where 'this' is context.

How to draw android animated Doughnut chart

Here I have use 'HoloGraph' Library for Doughnut chart But Now I need to show with animation. Please suggest me How can I do it?
I have done without animation
Here's how i finally did it after two days of search with help of this library https://github.com/Ken-Yang/AndroidPieChart
And equations to center text done with help of my friends and alot of search
on MainActivity onCreate or oncreateView if you are using fragments:
PieChart pie = (PieChart) rootView.findViewById(R.id.pieChart);
ArrayList<Float> alPercentage = new ArrayList<Float>();
alPercentage.add(2.0f);
alPercentage.add(8.0f);
alPercentage.add(20.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.0f);
alPercentage.add(10.85f);
alPercentage.add(9.15f);
try {
// setting data
pie.setAdapter(alPercentage);
// setting a listener
pie.setOnSelectedListener(new OnSelectedLisenter() {
#Override
public void onSelected(int iSelectedIndex) {
Toast.makeText(getActivity(),
"Select index:" + iSelectedIndex,
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
if (e.getMessage().equals(PieChart.ERROR_NOT_EQUAL_TO_100)) {
Log.e("kenyang", "percentage is not equal to 100");
}
}
public class PieChart extends View {
public interface OnSelectedLisenter {
public abstract void onSelected(int iSelectedIndex);
}
private OnSelectedLisenter onSelectedListener = null;
private static final String TAG = PieChart.class.getName();
public static final String ERROR_NOT_EQUAL_TO_100 = "NOT_EQUAL_TO_100";
private static final int DEGREE_360 = 360;
private static String[] PIE_COLORS = null;
private static int iColorListSize = 0;
ArrayList<Float> array;
private Paint paintPieFill;
private Paint paintPieBorder;
private Paint paintCenterCircle;
private ArrayList<Float> alPercentage = new ArrayList<Float>();
private int mCenterX = 320;
private int mCenterY = 320;
private int iDisplayWidth, iDisplayHeight;
private int iSelectedIndex = -1;
private int iCenterWidth = 0;
private int iShift = 0;
private int iMargin = 0; // margin to left and right, used for get Radius
private int iDataSize = 0;
private Canvas canvas1;
private RectF r = null;
private RectF centerCircle = null;
private float fDensity = 0.0f;
private float fStartAngle = 0.0f;
private float fEndAngle = 0.0f;
float fX;
float fY;
public PieChart(Context context, AttributeSet attrs) {
super(context, attrs);
PIE_COLORS = getResources().getStringArray(R.array.colors);
iColorListSize = PIE_COLORS.length;
array = new ArrayList<Float>();
fnGetDisplayMetrics(context);
iShift = (int) fnGetRealPxFromDp(30);
iMargin = (int) fnGetRealPxFromDp(40);
centerCircle = new RectF(200, 200, 440, 440);
// used for paint circle
paintPieFill = new Paint(Paint.ANTI_ALIAS_FLAG);
paintPieFill.setStyle(Paint.Style.FILL);
// used for paint centerCircle
paintCenterCircle = new Paint(Paint.ANTI_ALIAS_FLAG);
paintCenterCircle.setStyle(Paint.Style.FILL);
paintCenterCircle.setColor(Color.WHITE);
// used for paint border
paintPieBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
paintPieBorder.setStyle(Paint.Style.STROKE);
paintPieBorder.setStrokeWidth(fnGetRealPxFromDp(3));
paintPieBorder.setColor(Color.WHITE);
Log.i(TAG, "PieChart init");
}
// set listener
public void setOnSelectedListener(OnSelectedLisenter listener) {
this.onSelectedListener = listener;
}
float temp = 0;
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.i(TAG, "onDraw");
float centerX = (r.left + r.right) / 2;
float centerY = (r.top + r.bottom) / 2;
float radius1 = (r.right - r.left) / 2;
radius1 *= 0.5;
float startX = mCenterX;
float startY = mCenterY;
float radius = mCenterX;
float medianAngle = 0;
Path path = new Path();
for (int i = 0; i < iDataSize; i++) {
// check whether the data size larger than color list size
if (i >= iColorListSize) {
paintPieFill.setColor(Color.parseColor(PIE_COLORS[i
% iColorListSize]));
} else {
paintPieFill.setColor(Color.parseColor(PIE_COLORS[i]));
}
fEndAngle = alPercentage.get(i);
// convert percentage to angle
fEndAngle = fEndAngle / 100 * DEGREE_360;
// if the part of pie was selected then change the coordinate
if (iSelectedIndex == i) {
canvas.save(Canvas.MATRIX_SAVE_FLAG);
float fAngle = fStartAngle + fEndAngle / 2;
double dxRadius = Math.toRadians((fAngle + DEGREE_360)
% DEGREE_360);
fY = (float) Math.sin(dxRadius);
fX = (float) Math.cos(dxRadius);
canvas.translate(fX * iShift, fY * iShift);
}
canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieFill);
float angle = (float) ((fStartAngle + fEndAngle / 2) * Math.PI / 180);
float stopX = (float) (startX + (radius/2) * Math.cos(angle));
float stopY = (float) (startY + (radius/2) * Math.sin(angle));
// if the part of pie was selected then draw a border
if (iSelectedIndex == i) {
canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieBorder);
canvas.drawLine(startX, startY, stopX, stopY, paintPieFill);
canvas.restore();
}
fStartAngle = fStartAngle + fEndAngle;
}
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// get screen size
iDisplayWidth = MeasureSpec.getSize(widthMeasureSpec);
iDisplayHeight = MeasureSpec.getSize(heightMeasureSpec);
if (iDisplayWidth > iDisplayHeight) {
iDisplayWidth = iDisplayHeight;
}
/*
* determine the rectangle size
*/
iCenterWidth = iDisplayWidth / 2;
int iR = iCenterWidth - iMargin;
if (r == null) {
r = new RectF(iCenterWidth - iR, // top
iCenterWidth - iR, // left
iCenterWidth + iR, // right
iCenterWidth + iR); // bottom
}
if (centerCircle == null) {
// centerCircle=new RectF(left, top, right, bottom);
}
setMeasuredDimension(iDisplayWidth, iDisplayWidth);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// get degree of the touch point
double dx = Math.atan2(event.getY() - iCenterWidth, event.getX()
- iCenterWidth);
float fDegree = (float) (dx / (2 * Math.PI) * DEGREE_360);
fDegree = (fDegree + DEGREE_360) % DEGREE_360;
// get the percent of the selected degree
float fSelectedPercent = fDegree * 100 / DEGREE_360;
// check which pie was selected
float fTotalPercent = 0;
for (int i = 0; i < iDataSize; i++) {
fTotalPercent += alPercentage.get(i);
if (fTotalPercent > fSelectedPercent) {
iSelectedIndex = i;
break;
}
}
if (onSelectedListener != null) {
onSelectedListener.onSelected(iSelectedIndex);
}
invalidate();
return super.onTouchEvent(event);
}
private void fnGetDisplayMetrics(Context cxt) {
final DisplayMetrics dm = cxt.getResources().getDisplayMetrics();
fDensity = dm.density;
}
private float fnGetRealPxFromDp(float fDp) {
return (fDensity != 1.0f) ? fDensity * fDp : fDp;
}
public void setAdapter(ArrayList<Float> alPercentage) throws Exception {
this.alPercentage = alPercentage;
iDataSize = alPercentage.size();
float fSum = 0;
for (int i = 0; i < iDataSize; i++) {
fSum += alPercentage.get(i);
}
if (fSum != 100) {
Log.e(TAG, ERROR_NOT_EQUAL_TO_100);
iDataSize = 0;
throw new Exception(ERROR_NOT_EQUAL_TO_100);
}
}
In Layout:
<com.example.piecharts.PieChart
android:id="#+id/pieChart"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</com.example.piecharts.PieChart>

How to add a button to a bar chart without xml?

I have drawn a bar chart without xml.I have to add a button below the graph.Can anybody suggest solution.Thanks in Advance!!Following is my program.
GraphViewDemo.java
public class GraphViewDemo extends Activity {
public static String graphreturn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
float[] values = new float[] { 2.0f,3.0f, 5.0f, 1.0f , 6.0f , 4.0f ,7.0f };
String[] verlabels = new String[] { "7","6","5","4","3", "2", "1" };
String[] horlabels = new String[] {"jan20","jan21","jan22","jan23","jan24",
"jan25","jan26"};
GraphView graphView = new GraphView(this, values, "GraphViewDemo",horlabels, verlabels, GraphView.BAR);
setContentView(graphView);}}
GraphView.java
public class GraphView extends View{
public static boolean BAR = true;
public static boolean LINE = false;
private Paint paint;
private float[] values;
private String[] horlabels;
private String[] verlabels;
private String title;
private boolean type;
Context context;
private Drawable mDrawable;
private Runnable in ;
public GraphView(Context context, float[] values, String title, String[] horlabels,String[] verlabels, boolean type) {
super(context);
if (values == null)
values = new float[0];
else
this.values = values;
if (title == null)
title = "";
else
this.title = title;
if (horlabels == null)
this.horlabels = new String[0];
else
this.horlabels = horlabels;
if (verlabels == null)
this.verlabels = new String[0];
else
this.verlabels = verlabels;
this.type = type;
paint = new Paint();
}
#Override
protected void onDraw(final Canvas canvas) {
context=getContext();
float border = 20;
float horstart = border * 2;
float height = getHeight()-50;
float width = getWidth();
float max = getMax();
Log.w("max", ""+max);
float min = getMin();
Log.w("min", ""+min);
float diff = max - min;
float graphheight = height - (2 * border);
float graphwidth = width - (2 * border);
paint.setTextAlign(Align.LEFT);
int vers = verlabels.length - 1;
for (int i = 0; i < verlabels.length; i++) {
paint.setColor(Color.DKGRAY);
float y = ((graphheight / vers) * i) + border;
canvas.drawLine(horstart, y, width, y, paint);
paint.setColor(Color.WHITE);
canvas.drawText(verlabels[i], 0, y, paint);
}
int hors = horlabels.length;
for (int i = 0; i < horlabels.length; i++) {
paint.setColor(Color.DKGRAY);
float x = ((graphwidth / hors) * i) + horstart;
canvas.drawLine(x, height - border, x, border, paint);
paint.setTextAlign(Align.CENTER);
if (i==horlabels.length+5)
paint.setTextAlign(Align.RIGHT);
if (i==0)
paint.setTextAlign(Align.LEFT);
paint.setColor(Color.WHITE);
canvas.drawText(horlabels[i], x, height - 4, paint);
}
paint.setTextAlign(Align.CENTER);
canvas.drawText(title, (graphwidth / 2) + horstart, border - 4, paint);
int x = 0;
int y = 0;
Paint paint = new Paint();
Paint paint1 = new Paint();
paint.setStyle(Paint.Style.FILL);
String str2rotate = "Rotated!";
// draw bounding rect before rotating text
Rect rect = new Rect();
paint.getTextBounds(str2rotate, 0, str2rotate.length(), rect);
canvas.translate(x, y);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.STROKE);
paint1.setColor(Color.RED);
canvas.drawText("!Rotated", 0, 0, paint1);
mDrawable = context.getResources().getDrawable(R.drawable.previousi);
mDrawable.setBounds(getWidth()/2-40,getHeight()-40, getWidth()/2+30, getHeight()-20);
mDrawable.draw(canvas);
mDrawable.scheduleSelf(in, 0);
//....................
in = new Runnable() {
public void run() {
try {
//canvas.restore();
mDrawable.setBounds(getWidth()/2,getHeight(), getWidth(), getHeight()-20);
mDrawable.draw(canvas);
}
catch (Exception e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(null, in, "graphview");
thread.start();
if (max != min) {
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.FILL);
if (type == BAR) {
float datalength = values.length;
float colwidth = (width - (2 * border)) / datalength;
for (int i = 0; i < values.length; i++) {
float val = values[i] - min;
float rat = val / diff;
float h = graphheight * rat;
canvas.drawRect((i * colwidth) + horstart, (border - h) + graphheight, ((i * colwidth) + horstart) + (colwidth - 1), height - (border - 1), paint);
}
} else {
float datalength = values.length;
float colwidth = (width - (2 * border)) / datalength;
float halfcol = colwidth / 2;
float lasth = 0;
for (int i = 0; i < values.length; i++) {
float val = values[i] - min;
float rat = val / diff;
float h = graphheight * rat;
if (i > 0)
canvas.drawLine(((i - 1) * colwidth) + (horstart + 1) + halfcol, (border - lasth) + graphheight, (i * colwidth) + (horstart + 1) + halfcol, (border - h) + graphheight, paint);
lasth = h;
}
}
}
}
private float getMax() {
float largest = Integer.MIN_VALUE;
for (int i = 0; i < values.length; i++)
if (values[i] > largest)
largest = values[i];
return largest;
}
private float getMin() {
float smallest = Integer.MAX_VALUE;
for (int i = 0; i < values.length; i++)
if (values[i] < smallest)
smallest = values[i];
return smallest;
}
}
Try this:
btn = new Button(this);
btn.setText("Hello Button");
RelativeLayout.LayoutParams paramsd = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONT ENT,LayoutParams.WRAP_CONTENT);
paramsd.height = 60;
paramsd.width = 60;
btn.setLayoutParams(paramsd);
addContentView(btn,paramsd);
Edit:
import android.widget.Button;
Add button
Button b = new Button(this);
b.setText("Button added dynamically!");
b.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
b.setId(MY_BUTTON);
b.setOnClickListener(this);
ll.addView(b);
Edit2:
You could create LinearLayout linearLayout = new LinearLayout(this); and add Button
Button btn = new Button(this);
btn.setText("Just another button");
linearLayout.addView(btn);
Edit3: another example:
final Button button = new Button(this);
button.setText("Press me!");
setContentView(button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Huh? Just use XML. That you have this custom view is no barrier to its use. Here is a quick example of normal Android widgets in a layout with a custom widget:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tileview="http://schemas.android.com/apk/res/net.rapacity.wizardry"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/sokostatus"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/sokoban_status"/>
<net.rapacity.wizardry.TileView
android:id="#+id/sokomaze"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tileview:tileSize="32"/>
</LinearLayout>

Categories

Resources