displaying alert dialog in the correct location within a recyclerview - android-recyclerview

I'm making a custom button that when you long press on it a dialog will appear with a list of options to choose from.
The custom button works as it should, however, I'm having some trouble wrangling the dialog to show up exactly where I want it to.
this is the code that displays the dialog.
private void ShowReactionsDialog()
{
var context = Context;
var inflater = (LayoutInflater) context.GetSystemService(Context.LayoutInflaterService);
var dialogView = inflater.Inflate(Resource.Layout.react_dialog_layout, null);
var linearLayoutManager = new LinearLayoutManager(context)
{
Orientation = LinearLayoutManager.Horizontal
};
var adapter = new ReactionAdapter(_reactionList);
adapter.OnItemClicked += (sender, currentReaction) =>
{
UpdateReactButtonByReaction(currentReaction);
_reactAlertDialog.Cancel();
};
var rvReactions = dialogView.FindViewById<RecyclerView>(Resource.Id.reaction_rvReactions);
rvReactions.HasFixedSize = true;
rvReactions.SetLayoutManager(linearLayoutManager);
rvReactions.SetItemAnimator(new DefaultItemAnimator());
rvReactions.SetAdapter(adapter);
var dialogBuilder = new AlertDialog.Builder(context);
dialogBuilder.SetView(dialogView);
_reactAlertDialog = dialogBuilder.Create();
_reactAlertDialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
var window = _reactAlertDialog.Window;
window.SetBackgroundDrawableResource(Resource.Drawable.react_dialog_shape);
window.SetDimAmount(0);
// Setup dialog gravity and dynamic position
var windowManagerAttributes = window.Attributes;
windowManagerAttributes.Gravity = GravityFlags.AxisSpecified;
windowManagerAttributes.X = (int) GetX() + (Width / 2);
windowManagerAttributes.Y = (int) GetY() + (Height / 2);
_reactAlertDialog.Show();
var dialogWidth = GetIconSize() * _reactionList.Count;
if (dialogWidth > GetScreenMaxWidth())
{
dialogWidth = GetScreenMaxWidth();
}
window.SetLayout(dialogWidth, ViewGroup.LayoutParams.WrapContent);
}
I've tried messing with the gravity and the X & Y coordinates but it just wants to either go too high up or too low down, there's no consistent location it's sticking to. I want it to be above the button that's getting long tapped.

You can use the following code to make the AlertDialog show above the button.
int[] location = new int[2];
AndroidX.AppCompat.App.AlertDialog alertDialog = builder.Create();
Window window = alertDialog.Window;
WindowManagerLayoutParams attributes = window.Attributes;
//Get the location of the button and location[0] is X and location[1] is Y
button.GetLocationInWindow(location);
//Set the height of the AlertDialog
int height = 400;
int a = button.Height / 2;
int c = location[1];
//Get the distance of top
attributes.Y = c - a - height;
window.Attributes = attributes;
//Set the AlertDialog location according to the distance of top
window.SetGravity(GravityFlags.Top);
alertDialog.Show();
//Set the Width and Hight of the AlertDialog
alertDialog.Window.SetLayout(800, height);

Related

adobe illustrator script- rectangle resize

×™ello everybody! I tried to create a script that creats a rectangle of a given size, make a group and a clipping mask and after all that resize it to a diffrent size in mm.
for example I have a graphic with the name "fish400" and I clip it in a rectangle of 400X400 that I create with the script. so far so good. my problem is that I want to resize the clipping with all it's content to 382. when I set the height to be the rec. size-18 it gets the height of 385.1
I'm not a very skilled programmer and the script could be written better but I really don't get my mistake.
here is my code:
var doc = app.activeDocument;
var layers = doc.layers;
var myLayer = layers["Layer 1"]; //this defines the layer that you want to get the selection from
var vals = 0;
var tzim = 0;
var side = 0; //width || height
//mm convertor
function mm(n) {return n * 2.83464566929134;}
doc.selection = null; //ensure there is nothing in the document selected already. this way you only get the selection you want.
var found = false;
for(var a=0 ;a<doc.groupItems.length; a++)
{
if (doc.groupItems[a].name == "fish400") {vals = mm(400); tzim = mm(18); side = 1; found = true;}
}
if (found = true)
{
var rect = doc.pathItems.rectangle(0,0,vals,vals);
app.executeMenuCommand("selectall");
var groupItem = doc.groupItems.add();
var count = selection.length;
for(var i = 0; i < count; i++)
{
var item = selection[selection.length - 1];
item.moveToBeginning(groupItem);
}
groupItem.clipped = true;
item.top = center_point[0] + (item.height/2);
item.left = center_point[1] - (item.width/2);
if (side == 1) {groupItem.height -= tzim;} else if (side == 0) {groupItem.width -= tzim;}
}
If your script works fine for you (it doesn't work for me, though) and all you want is to add resizing for your picture from 400x400 to 382x382 mm you can just to add at the end of your script these lines:
var k = 382/400*100;
groupItem.resize(k,k);
Or:
app.executeMenuCommand("selectall");
var sel = app.selection[0];
var k = 382/400*100;
sel.resize(k,k);

Screenshot using SharpDX and EasyHook transparent

I have been struggling in taking screenshots with DirectX, the problem is, it's working but seems to be missing some colors (black outline is missing for example), and some stuff that is also rendered by DX doesn't show.
I have uploaded the images (how the image should render and the rendered one) and also the code, what might be the issue?
Correct Image
Rendered Image
Greetings
public class Screenshot
{
public static void TakeScreenshot(string name = null)
{
var t = new Thread((ThreadStart) delegate
{
// destination folder
var destinationFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.Create) + "\\My Software\\Screenshots";
if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder);
// file name
string filename = name;
if (string.IsNullOrEmpty(name))
filename = "image-" + (Directory.GetFiles(destinationFolder, "*.png").Count() + 1).ToString("000") + ".png";
// # of graphics card adapter
const int numAdapter = 0;
// # of output device (i.e. monitor)
const int numOutput = 0;
// Create DXGI Factory1
var factory = new Factory1();
var adapter = factory.GetAdapter1(numAdapter);
// Create device from Adapter
var device = new Device(adapter);
// Get DXGI.Output
var output = adapter.GetOutput(numOutput);
var output1 = output.QueryInterface<Output1>();
// Width/Height of desktop to capture
int width = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width;
int height = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height;
// Create Staging texture CPU-accessible
var textureDesc = new Texture2DDescription
{
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = width,
Height = height,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
var screenTexture = new Texture2D(device, textureDesc);
// Duplicate the output
var duplicatedOutput = output1.DuplicateOutput(device);
bool captureDone = false;
for (int i = 0; !captureDone; i++)
{
try
{
SharpDX.DXGI.Resource screenResource;
OutputDuplicateFrameInformation duplicateFrameInformation;
// Try to get duplicated frame within given time
duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource);
if (i > 0)
{
// copy resource into memory that can be accessed by the CPU
using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
// Get the desktop capture texture
var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);
// Create Drawing.Bitmap
var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);
// Copy pixels from screen capture Texture to GDI bitmap
var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
var sourcePtr = mapSource.DataPointer;
var destPtr = mapDest.Scan0;
for (int y = 0; y < height; y++)
{
// Copy a single line
Utilities.CopyMemory(destPtr, sourcePtr, width * 4);
// Advance pointers
sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
destPtr = IntPtr.Add(destPtr, mapDest.Stride);
}
// Release source and dest locks
bitmap.UnlockBits(mapDest);
device.ImmediateContext.UnmapSubresource(screenTexture, 0);
// Save the output
bitmap.Save(destinationFolder + Path.DirectorySeparatorChar + filename);
// Send Message
Main.Chat.AddMessage(null, "~b~Screenshot saved as " + filename);
// Capture done
captureDone = true;
}
screenResource.Dispose();
duplicatedOutput.ReleaseFrame();
}
catch (SharpDXException e)
{
if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
{
throw e;
}
}
}
});
t.IsBackground = true;
t.Start();
}
}

How do I add a radius line from the center of the circle to a point on the circle

The following code adds a circle of given radius to the graphics layer on an ArcGIS map. How can I add a line that joins center of the circle to any point on the circle to the graphics layer.
Basically the question is how do I calculate a point on the circle, draw a line that joins the center to the point on the circle and add it to the graphics layer.
performSearchPoint : function(e) {
var self = this;
var radius = $('#radius-distance').val();
if(radius > 0 && radius < 100000){
$('#besideMouse').removeClass('hide');
$('#besideMouse').show();
var loadingBMint = setInterval(this.loadingBM, 0);
var searchPointClick = OURAPP.App.Map.on("click",function(evt) {
loadingBMint = clearInterval(loadingBMint);
$('#besideMouse').hide();
var radius = $('#radius-distance').val();
var units = $("input:radio[name='unitsGroup']:checked").val();
if (units == "miles"){
units = "9035"; // if we use GeometryService
} else {
units = "9003"; // if we use GeometryService
}
//clear only search graphics
for ( var gr in OURAPP.App.Map.graphics.graphics) {
if(OURAPP.App.Map.graphics.graphics[gr].infoTemplate != null){
var template = OURAPP.App.Map.graphics.graphics[gr].infoTemplate;
if(template != "undefined" || template != null){
if(template.title.trim() == "Search Graphic"){
OURAPP.App.Map.graphics.remove(OURAPP.App.Map.graphics.graphics[gr]);
}
}}}
/*do buffer geometry for draw circle and use the circle geometry to get the features*/
var geoService = new OURAPP.esri.GeometryService("http://XXXX:YYYY/arcgis/rest/services/Utilities/Geometry/GeometryServer");
var params = new OURAPP.esri.BufferParameters();
params.geometries = [ evt.mapPoint ];
params.distances = [ radius ];
params.unit = units;
params.bufferSpatialReference = OURAPP.App.Map.spatialReference;
params.outSpatialReference = new OURAPP.esri.SpatialReference(4326);
var bufferPolygon = new OURAPP.esri.Polygon;
bufferPolygon.spatialReference = new OURAPP.esri.SpatialReference(4326);
geoService.buffer(params,function(geometries) {
var symbol = new OURAPP.esri.SimpleFillSymbol()
.setColor(null).outline.setColor("red");
dojo.forEach(geometries,function(geometry) {
geometry.spatialReference = new OURAPP.esri.SpatialReference(4326);
var graphic = new OURAPP.esri.Graphic(geometry,symbol);
// add name to identify the search graphics
var template = new OURAPP.esri.InfoTemplate(graphic.geometry);
template.setTitle("Search Graphic");
template.setContent("Map Query circle with Radius: " + radius);
graphic.setInfoTemplate(template);
OURAPP.App.Map.graphics.add(graphic);
bufferPolygon = geometry;
OURAPP.App.Map.setExtent(graphic.geometry.getExtent().expand(2));
});
self.searchType="Distance Search from point";
self.nameofplace=radius + " "+$("input:radio[name='unitsGroup']:checked").val();
self.showCount(bufferPolygon);
});
searchPointClick.remove();
});
}
},
I was able to draw a line and add it to the graphics layer using the following. The [-XX.XXXXXXXXXXXX,YY.YYYYYYYYYYY] is a random point on the map, Now only thing left is to find a point on a circle. So now the question becomes how to find a point which is X miles from a known point(Center of the circle) along the same latitude.
var lineSymbol = new OURAPP.esri.CartographicLineSymbol(
OURAPP.esri.CartographicLineSymbol.STYLE_SOLID,
new OURAPP.esri.Color([255,0,0]), 2,
OURAPP.esri.CartographicLineSymbol.CAP_SQUARE,
OURAPP.esri.CartographicLineSymbol.JOIN_MITER, 5
);
var lineGeometry = new OURAPP.esri.Polyline;
lineGeometry.spatialReference = new OURAPP.esri.SpatialReference(4326);
lineGeometry.addPath([[evt.mapPoint.getLongitude(),evt.mapPoint.getLatitude()], [-XX.XXXXXXXXXXXX,YY.YYYYYYYYYYY]])
var lineGraphic = new OURAPP.esri.Graphic(lineGeometry, lineSymbol);
OURAPP.App.Map.graphics.add(lineGraphic);
This is the best possible one i came up with and its working.
var lineSymbol = new OURAPP.esri.CartographicLineSymbol(
OURAPP.esri.CartographicLineSymbol.STYLE_SOLID,
new OURAPP.esri.Color([255,0,0]), 2,
OURAPP.esri.CartographicLineSymbol.CAP_SQUARE,
OURAPP.esri.CartographicLineSymbol.JOIN_MITER, 5
);
var radiusInMeters;
if (selectedUnit == "miles"){
radiusInMeters = radius*1609.34; //have to convert it to meters.
} else {
radiusInMeters = radius*0.3048; //have to convert it to meters.
}
// Calculate the new map point on the circle.
var radians = Math.PI/180;
var ltLong = OURAPP.esri.webMercatorUtils.xyToLngLat(evt.mapPoint.x + radiusInMeters*Math.cos(radians), evt.mapPoint.y + radiusInMeters*Math.sin(radians));
// Calculate the new map point on the circle.
var lineGeometry = new OURAPP.esri.Polyline;
lineGeometry.spatialReference = new OURAPP.esri.SpatialReference(4326);
lineGeometry.addPath([[evt.mapPoint.getLongitude(),evt.mapPoint.getLatitude()], ltLong]);
var lineGraphic = new OURAPP.esri.Graphic(lineGeometry, lineSymbol);

ThreeJS. How to implement ZoomALL and make sure a given box fills the canvas area?

I am looking for a function to ensure that a given box or sphere will be visible in a WebGL canvas, and that it will fit the canvas area.
I am using a perspective camera and the camera already points to the middle of the object.
I understand that this could be achieved by changing the FOV angle or by moving the camera along the view axis.
Any idea how this could be achieved with ThreeJS ?
This is how I finally implemented it:
var camera = new THREE.PerspectiveCamera(35,1,1, 100000);
var controls = new THREE.TrackballControls( me.camera , container);
[...]
/**
* point the current camera to the center
* of the graphical object (zoom factor is not affected)
*
* the camera is moved in its x,z plane so that the orientation
* is not affected either
*/
function pointCameraTo (node) {
var me = this;
// Refocus camera to the center of the new object
var COG = shapeCenterOfGravity(node);
var v = new THREE.Vector3();
v.subVectors(COG,me.controls.target);
camera.position.addVectors(camera.position,v);
// retrieve camera orientation and pass it to trackball
camera.lookAt(COG);
controls.target.set( COG.x,COG.y,COG.z );
};
/**
* Zoom to object
*/
function zoomObject (node) {
var me = this;
var bbox = boundingBox(node);
if (bbox.empty()) {
return;
}
var COG = bbox.center();
pointCameraTo(node);
var sphereSize = bbox.size().length() * 0.5;
var distToCenter = sphereSize/Math.sin( Math.PI / 180.0 * me.camera.fov * 0.5);
// move the camera backward
var target = controls.target;
var vec = new THREE.Vector3();
vec.subVectors( camera.position, target );
vec.setLength( distToCenter );
camera.position.addVectors( vec , target );
camera.updateProjectionMatrix();
render3D();
};
An example of this can be seen in https://github.com/OpenWebCAD/node-occ-geomview/blob/master/client/geom_view.js
Here is how I did it { Using TrackBall to Zoomin/out pan etc }
function init(){
......
......
controls = new THREE.TrackballControls(camera);
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;
controls.keys = [65, 83, 68];
controls.addEventListener('change', render);
.....
.....
render(scene, camera);
animate();
}
function render()
{
renderer.render(scene, camera);
//stats.update();
}
function animate() {
requestAnimationFrame(animate);
controls.update();
}

How to have a custom side bar slide from right in your metro app?

I am developing a metro app where , I want to have a customized bar slide when the user clicks on something in the screen.
This is what i am talking about :-
--------------
| | |
| | | <----
| | |
---------------
main screen side
bar
In this side bar i want have some simple controls like image and text block etc..
1) How can i do this , any help would be appreciated
2) Its not against metro principles right ?
You could try to leverage a flyout like the settings flyout. You might want to look at Callisto.
You could otherwise include a Xaml element that above all others and toggle it's visibility along with a positioning right on the screen. How to position depends on what root element you're using. For positioning an element in a canvas add Canvas.Right="0" to the child element.
You can use PopUp.
have a look at this example,
http://code.msdn.microsoft.com/windowsapps/App-settings-sample-1f762f49
you can use following helper
WinRT Flyout Helper
public class FlyoutHelper
{
protected Popup m_Popup = new Popup();
public Popup Show(Popup popup, FrameworkElement button, double offset = 35d)
{
if (popup == null)
throw new Exception("Popup is not defined");
m_Popup = popup;
if (button == null)
throw new Exception("Button is not defined");
if (double.IsNaN(offset))
throw new Exception("Offset is not defined");
var _Child = popup.Child as FrameworkElement;
if (_Child == null)
throw new Exception("Popup.Child is not defined");
if (double.IsNaN(_Child.Height))
throw new Exception("Popup.Child.Height is not defined");
if (double.IsNaN(_Child.Width))
throw new Exception("Popup.Child.Width is not defined");
// get position of the button
var _Page = Window.Current.Content as Page;
var _Visual = button.TransformToVisual(_Page);
var _Point = _Visual.TransformPoint(new Point(0, 0));
var _Button = new
{
Top = _Point.Y,
Left = _Point.X,
Width = button.ActualWidth,
Height = button.ActualHeight,
};
// determine location
var _TargetTop = (_Button.Top + (_Button.Height / 2)) -
_Child.Height - offset;
var _TargetLeft = (_Button.Left + (_Button.Width / 2)) -
(_Child.Width / 2);
if ((_TargetLeft + _Child.Width) > Window.Current.Bounds.Width)
_TargetLeft = Window.Current.Bounds.Width - _Child.Width - offset;
if (_TargetLeft < 0)
_TargetLeft = offset;
// setup popup
popup.VerticalOffset = _TargetTop;
popup.HorizontalOffset = _TargetLeft;
// add pretty animation(s)
popup.ChildTransitions = new TransitionCollection
{
new EntranceThemeTransition
{
FromHorizontalOffset = 0,
FromVerticalOffset = 20
}
};
// setup
m_Popup.IsLightDismissEnabled = true;
m_Popup.IsOpen = true;
// handle when it closes
m_Popup.Closed -= popup_Closed;
m_Popup.Closed += popup_Closed;
// handle making it close
Window.Current.Activated -= Current_Activated;
Window.Current.Activated += Current_Activated;
// return
return m_Popup;
}
protected void Current_Activated(object sender, WindowActivatedEventArgs e)
{
if (m_Popup == null)
return;
if (e.WindowActivationState == CoreWindowActivationState.Deactivated)
m_Popup.IsOpen = false;
}
protected void popup_Closed(object sender, object e)
{
Window.Current.Activated -= Current_Activated;
if (m_Popup == null)
return;
m_Popup.IsOpen = false;
}
}
For this you can use CharmFlyout.
Here is the sample code http://code.msdn.microsoft.com/windowsapps/CharmFlyout-A-Metro-Flyout-25fe53b6