set coordinates as center of imageview Android programmatically - android-layout

I have coordinates to align imageviews on these, programmatically. And right now images are being aligned but the image starts from this coordinate or I should say that the coordinate becomes its top left corner of my imageview and I want to make it center of my imageview. how to make coordinate center of imageview? Right now I'm doing this:
ImageView iv = new ImageView(this);
float x_coordinate = 256;
float y_coordinate = 350;
iv.setX(x_coordinate);
iv.setY(y_coordinate);
iv.setImageResource(R.drawable.myimage);
iv.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
mylayout.addView(iv);

I didn't find the simple one line solution but i solved my problem doing the following procedure. Here Place is my model class of which getX_Cord() and getY_Cord() returns the x and y coordinate of image, And you have to save an image in your drawable folder of which size you want to set on your screen in my case this is R.drawable.placeImage.
// display parameters
Point size = new Point();
Display display = getWindowManager().getDefaultDisplay();
display.getSize(size);
width = size.x;
height = size.y;
final Place place = roomPlace.get(i);
Drawable d = getResources().getDrawable(R.drawable.placeImage);
int y = d.getIntrinsicHeight() / 2;
int x = d.getIntrinsicWidth() / 2;
placeImage.setX((place.getX_Cord() * width) - x);
placeImage.setY((place.getY_Cord() * height) - y);
May be someone gets with more appropriate solution but i solved my problem doing this.

Related

How to get position/off-set of an element in android with respect to parent element?

In my project I have a layout like:
<FrameLayout> ---------(1)
<SurfaceView>
<FrameLayout> ------(2)
</SurfaceView>
</FrameLayout>
I want to access position/offset of frame-layout (2) with respect to frame-layout (1).
When I try FrameLayout1.getLeft() and FrameLayout1.getTop(), I get it as zero.
What is the correct way to get the (left,top) of nested elements?
Thank you!
Update--->
int dpi = getResources().getDisplayMetrics().densityDpi;
int offset1 = childFrameLayoutPosition[0] - rootFrameLayoutPosition[0]; //x offset
int offset2 = childFrameLayoutPosition[1] - rootFrameLayoutPosition[1]; //y offset
//F1 is child FrameLayout
newBitmap = Bitmap.createBitmap(bitmap,offset1*w, offset2*w,F1.getWidth()*w,F1.getHeight()*w);
After doing this, I got error that Width and Height parameters should be less than width and height of bitmap.
int[] rootFrameLayoutPosition = new int[2];
int[] childFrameLayoutPosition = new int[2];
rootFrameLayout.getLocationInWindow(rootFrameLayoutPosition);
childFrameLayout.getLocationInWindow(childFrameLayoutPosition);
int offset = childFrameLayoutPosition[1] - rootFrameLayoutPosition[1];
maybe I'm confused x and y

How can i draw circle at Xamarin?

Hello dear developers,
Im using xamarin (monotouch) i want to draw circle image view like google plus profile image or like otherones...
I was search on net but didnt find useful thing.
Somebody help me?
Thank you..
For your purposes you can use UIView or UIButton. With UIButton it is easier to handle touch events.
The basic idea is to create a UIButton with specific coordinates and size and set the CornerRadius property to be one half of the size of the UIButton (assuming you want to draw a circle, width and height will be the same).
Your code could look something like this (in ViewDidLoad of your UIViewController):
// define coordinates and size of the circular view
float x = 50;
float y = 50;
float width = 200;
float height = width;
// corner radius needs to be one half of the size of the view
float cornerRadius = width / 2;
RectangleF frame = new RectangleF(x, y, width, height);
// initialize button
UIButton circularView = new UIButton(frame);
// set corner radius
circularView.Layer.CornerRadius = cornerRadius;
// set background color, border color and width to see the circular view
circularView.BackgroundColor = UIColor.White;
circularView.Layer.CornerRadius = cornerRadius;
circularView.Layer.BorderColor = UIColor.Red.CGColor;
circularView.Layer.BorderWidth = 5;
// handle touch up inside event of the button
circularView.TouchUpInside += HandleCircularViewTouchUpInside;
// add button to view controller
this.View.Add(circularView);
At last implement the event handler (define this method somewhere in your UIViewController:
private void HandleCircularViewTouchUpInside(object sender, EventArgs e)
{
// initialize random
Random rand = new Random(DateTime.Now.Millisecond);
// when the user 'clicks' on the circular view, randomly change the border color of the view
(sender as UIButton).Layer.BorderColor = UIColor.FromRGB(rand.Next(255), rand.Next(255), rand.Next(255)).CGColor;
}
Xamarin.iOS is a wrapper over Cocoa Touch on UI side,
https://developer.apple.com/technologies/ios/cocoa-touch.html
So to draw circle you need to use the Cocoa Touch API, aka CoreGraphics,
http://docs.xamarin.com/videos/ios/getting-started-coregraphics/

Arc menu item style like in tumblr app for Android

I tweaked https://github.com/daCapricorn/ArcMenu library to make it work from my purpose and that is working fine. Is there anyway I can build a menu like as in tumblr app or is it possible by tweaking the ArcMenu project or https://github.com/siyamed/android-satellite-menu ? I have doubts on the mathematical functions to be applied to create the style.
I am looking for a animation similar to tumblr app's animation.
try to use , Arc Menu
implement RayMenu and modify RayLayout
and modify the private static AnimationcreateExpandAnimation()` method with your specific coordinate.
There are many ways I do this in iOS. In iOS we have Views similar to that of Android and we can specify coordinates (frame of view) to place them in their superview.
Assumptions :
1)Assume you have a locus i.e circle with equation x^2 + y^2 = c
( Hint : All views are on this locus i.e center of all views coincide with this circle)
2) You need select a value of C depending on the curve you need and initial point which is
(0,HEIGHT_OF_SCREEN) as stating point for placing views.
Algorithm :
int angularDisplacementBetweenEachView = 10; // distance between two views in radians
// coordinates of X button in your screen
int startPositionOfViewX = 0;
int startPositionOfViewY = HEIGHT_OF_SCREEN;
// constant to decide curve
int C = 125;
-(void) main (){ // this is generally done in view controller
for(int i = 1; i< menu_items.count; i++){
Rect position = getCoordinatesForView(menu_item.get(i),menu_item.get(i-1).rect.x,menu_item.get(i-1).rect.y);
addView(menu_item.get(i),position.x,position.y);
}
}
// method returns the coordinates (x,y) at which the view is required to be
//placed.
-(Rect)getCoordinatesForView(View currentView, int prevViewX, int prevViewY){
// convert to polar cordinates
// refer diagram
// this is also the radius of the virtual circle
float r = sqrt(pow(x,2),pow(y,2));
float theta = atan(y,x);
//r & theta are polar coordinates of previous menu item
float theta2 = (angularDisplacementBetweenEachView + r*theta)/r;
// convert back to cartesian coordinates
int x2 = r * cos (theta);
int y2 = r * sin (theta);
return new rect(x2,y2);
}
try this for Arc menu. u can use this sattelite menu
https://github.com/ketanpatel25/android-satellite-menu-center

Trying to draw Rotated text with CGAffineTransform and MakeRotation appears at wrong location

I'm trying to draw some rotated texts by using the CGAffineTransform.MakeRotation method at specifc location. I also make use of the TranslateCTM, but something must be wrong as rotated texts do not appear aligned and at the correct x, y position where they should appear, here is simple the code I'm using, anyone know where the problem is? :
public override void Draw (RectangleF rect)
{
DrawTextRotated("Hello1",10,100,30);
DrawTextRotated("Hello2",50,100,60);
SetNeedsDisplay();
}
static public float DegreesToRadians(float x)
{
return (float) (Math.PI * x / 180.0);
}
public void DrawTextRotated(string text,int x, int y, int rotDegree)
{
CGContext c = UIGraphics.GetCurrentContext();
c.SaveState();
c.TextMatrix = CGAffineTransform.MakeRotation((float)DegreesToRadians((float)(-rotDegree)));
c.ConcatCTM(c.TextMatrix);
float xxx = ((float)Math.Sin(DegreesToRadians((float)rotDegree))*y);
float yyy = ((float)Math.Sin(DegreesToRadians((float)rotDegree))*x);
// Move the context back into the view
c.TranslateCTM(-xxx,yyy);
c.SetTextDrawingMode(CGTextDrawingMode.Fill);
c.SetShouldSmoothFonts(true);
MonoTouch.Foundation.NSString str = new MonoTouch.Foundation.NSString(text);
SizeF strSize = new SizeF();
strSize = str.StringSize(UIFont.SystemFontOfSize(12));
RectangleF tmpR = new RectangleF(x,y,strSize.Width,strSize.Height);
str.DrawString(tmpR,UIFont.SystemFontOfSize(12),UILineBreakMode.WordWrap,UITextAlignment.Right);
c.RestoreState();
}
Thanks !
Here's some code that will draw text rotated properly about the top-left corner of the text. For the moment, I'm disregarding your use of text alignment.
First, a utility method to draw a marker where we expect the text to show up:
public void DrawMarker(float x, float y)
{
float SZ = 20;
CGContext c = UIGraphics.GetCurrentContext();
c.BeginPath();
c.AddLines( new [] { new PointF(x-SZ,y), new PointF(x+SZ,y) });
c.AddLines( new [] { new PointF(x,y-SZ), new PointF(x,y+SZ) });
c.StrokePath();
}
And the code to draw the text (note I've replaced all int rotations with float, and you may want negate your rotation):
public void DrawTextRotated(string text, float x, float y, float rotDegree)
{
CGContext c = UIGraphics.GetCurrentContext();
c.SaveState();
DrawMarker(x,y);
// Proper rotation about a point
var m = CGAffineTransform.MakeTranslation(-x,-y);
m.Multiply( CGAffineTransform.MakeRotation(DegreesToRadians(rotDegree)));
m.Multiply( CGAffineTransform.MakeTranslation(x,y));
c.ConcatCTM( m );
// Draws text UNDER the point
// "This point represents the top-left corner of the string’s bounding box."
//http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html
NSString ns = new NSString(text);
UIFont font = UIFont.SystemFontOfSize(12);
SizeF sz = ns.StringSize(font);
RectangleF rect = new RectangleF(x,y,sz.Width,sz.Height);
ns.DrawString( rect, font);
c.RestoreState();
}
Rotation about a point requires translation of the point to the origin followed by rotation, followed by rotation back to the original point. CGContext.TextMatrix has no effect on NSString.DrawString so you can just use ConcatCTM.
The alignment and line break modes don't have any effect. Since you're using NSString.StringSize, the bounding rectangle fits the entirety of the text, snug up against the left and right edges. If you make the width of the bounding rectangle wider and use UITextAlignment.Right, you'll get proper right alignment, but the text will still rotate around the top left corner of the entire bounding rectangle. Which is not, I'm guessing, what you're expecting.
If you want the text to rotate around the top right corner, let me know and I'll adjust the code accordingly.
Here's the code I used in my test:
DrawTextRotated("Hello 0",100, 50, 0);
DrawTextRotated("Hello 30",100,100,30);
DrawTextRotated("Hello 60",100,150,60);
DrawTextRotated("Hello 90",100,200,90);
Cheers.

Rotating an Image in Silverlight without cropping

I am currently working on a simple Silverlight app that will allow people to upload an image, crop, resize and rotate it and then load it via a webservice to a CMS.
Cropping and resizing is done, however rotation is causing some problems. The image gets cropped and is off centre after the rotation.
WriteableBitmap wb = new WriteableBitmap(destWidth, destHeight);
RotateTransform rt = new RotateTransform();
rt.Angle = 90;
rt.CenterX = width/2;
rt.CenterY = height/2;
//Draw to the Writeable Bitmap
Image tempImage2 = new Image();
tempImage2.Width = width;
tempImage2.Height = height;
tempImage2.Source = rawImage;
wb.Render(tempImage2,rt);
wb.Invalidate();
rawImage = wb;
message.Text = "h:" + rawImage.PixelHeight.ToString();
message.Text += ":w:" + rawImage.PixelWidth.ToString();
//Finally set the Image back
MyImage.Source = wb;
MyImage.Width = destWidth;
MyImage.Height = destHeight;
The code above only needs to rotate by 90° at this time so I'm just setting destWidth and destHeight to the height and width of the original image.
It looks like your target image is the same size as your source image. If you want to rotate over 90 degrees, your width and height should be exchanged:
WriteableBitmap wb = new WriteableBitmap(destHeight, destWidth);
Also, if you rotate about the centre of the original image, part of it will end up outside the boundaries. You could either include some translation transforms, or simply rotate the image about a different point:
rt.CenterX = rt.CenterY = Math.Min(width / 2, height / 2);
Try it with a piece of rectangular paper to see why that makes sense.
Many thanks to those above.. they helped a lot. I include here a simple example which includes the additional transform necessary to move the rotated image back to the top left corner of the result.
int width = currentImage.PixelWidth;
int height = currentImage.PixelHeight;
int full = Math.Max(width, height);
Image tempImage2 = new Image();
tempImage2.Width = full;
tempImage2.Height = full;
tempImage2.Source = currentImage;
// New bitmap has swapped width/height
WriteableBitmap wb1 = new WriteableBitmap(height,width);
TransformGroup transformGroup = new TransformGroup();
// Rotate around centre
RotateTransform rotate = new RotateTransform();
rotate.Angle = 90;
rotate.CenterX = full/2;
rotate.CenterY = full/2;
transformGroup.Children.Add(rotate);
// and transform back to top left corner of new image
TranslateTransform translate = new TranslateTransform();
translate.X = -(full - height) / 2;
translate.Y = -(full - width) / 2;
transformGroup.Children.Add(translate);
wb1.Render(tempImage2, transformGroup);
wb1.Invalidate();
If the image isn't square you will get cropping.
I know this won't give you exactly the right result, you'll need to crop it afterwards, but it will create a bitmap big enough in each direction to take the rotated image.
//Draw to the Writeable Bitmap
Image tempImage2 = new Image();
tempImage2.Width = Math.Max(width, height);
tempImage2.Height = Math.Max(width, height);
tempImage2.Source = rawImage;
You need to calculate the scaling based on the rotation of the corners relative to the centre.
If the image is a square only one corner is needed, but for a rectangle you need to check 2 corners in order to see if a vertical or horizontal edge is overlapped. This check is a linear comparison of how much the rectangle's height and width are exceeded.
Click here for the working testbed app created for this answer (image below):
double CalculateConstraintScale(double rotation, int pixelWidth, int pixelHeight)
The pseudo-code is as follows (actual C# code at the end):
Convert rotation angle into Radians
Calculate the "radius" from the rectangle centre to a corner
Convert BR corner position to polar coordinates
Convert BL corner position to polar coordinates
Apply the rotation to both polar coordinates
Convert the new positions back to Cartesian coordinates (ABS value)
Find the largest of the 2 horizontal positions
Find the largest of the 2 vertical positions
Calculate the delta change for horizontal size
Calculate the delta change for vertical size
Return width/2 / x if horizontal change is greater
Return height/2 / y if vertical change is greater
The result is a multiplier that will scale the image down to fit the original rectangle regardless of rotation.
**Note: While it is possible to do much of the maths using matrix operations, there are not enough calculations to warrant that. I also thought it would make a better example from first-principles.*
C# Code:
/// <summary>
/// Calculate the scaling required to fit a rectangle into a rotation of that same rectangle
/// </summary>
/// <param name="rotation">Rotation in degrees</param>
/// <param name="pixelWidth">Width in pixels</param>
/// <param name="pixelHeight">Height in pixels</param>
/// <returns>A scaling value between 1 and 0</returns>
/// <remarks>Released to the public domain 2011 - David Johnston (HiTech Magic Ltd)</remarks>
private double CalculateConstraintScale(double rotation, int pixelWidth, int pixelHeight)
{
// Convert angle to radians for the math lib
double rotationRadians = rotation * PiDiv180;
// Centre is half the width and height
double width = pixelWidth / 2.0;
double height = pixelHeight / 2.0;
double radius = Math.Sqrt(width * width + height * height);
// Convert BR corner into polar coordinates
double angle = Math.Atan(height / width);
// Now create the matching BL corner in polar coordinates
double angle2 = Math.Atan(height / -width);
// Apply the rotation to the points
angle += rotationRadians;
angle2 += rotationRadians;
// Convert back to rectangular coordinate
double x = Math.Abs(radius * Math.Cos(angle));
double y = Math.Abs(radius * Math.Sin(angle));
double x2 = Math.Abs(radius * Math.Cos(angle2));
double y2 = Math.Abs(radius * Math.Sin(angle2));
// Find the largest extents in X & Y
x = Math.Max(x, x2);
y = Math.Max(y, y2);
// Find the largest change (pixel, not ratio)
double deltaX = x - width;
double deltaY = y - height;
// Return the ratio that will bring the largest change into the region
return (deltaX > deltaY) ? width / x : height / y;
}
Example of use:
private WriteableBitmap GenerateConstrainedBitmap(BitmapImage sourceImage, int pixelWidth, int pixelHeight, double rotation)
{
double scale = CalculateConstraintScale(rotation, pixelWidth, pixelHeight);
// Create a transform to render the image rotated and scaled
var transform = new TransformGroup();
var rt = new RotateTransform()
{
Angle = rotation,
CenterX = (pixelWidth / 2.0),
CenterY = (pixelHeight / 2.0)
};
transform.Children.Add(rt);
var st = new ScaleTransform()
{
ScaleX = scale,
ScaleY = scale,
CenterX = (pixelWidth / 2.0),
CenterY = (pixelHeight / 2.0)
};
transform.Children.Add(st);
// Resize to specified target size
var tempImage = new Image()
{
Stretch = Stretch.Fill,
Width = pixelWidth,
Height = pixelHeight,
Source = sourceImage,
};
tempImage.UpdateLayout();
// Render to a writeable bitmap
var writeableBitmap = new WriteableBitmap(pixelWidth, pixelHeight);
writeableBitmap.Render(tempImage, transform);
writeableBitmap.Invalidate();
return writeableBitmap;
}
I released a Test-bed of the code on my website so you can try it for real - click to try it
P.S. Yes this is my answer from another question, duplicated exactly, but the question does require the same answer as that one to be complete.

Resources