RDLC Reports Proportional Image Alignment - image

I'm working on an RDLC Report ,I use a DB Image, and set it's size type to Proportional, if the image isn't the exact size as it's borders, borders won't fit .. this is ok, but the image will be aligned top-left according to borders while I need it to be centered (on PDF) while on IE it's centered .., here are image examples,, Please I Need Help for this ..
This is the I Already Have
http://up.g4z4.com/uploads/f1fdee3542.jpg
This is the Desired One
http://up.g4z4.com/uploads/a3d2ca5b8e.jpg
I read once that the image origin or Registration Point in RDLC Reports is on the top left, that's why it shows like this .. but the one who wrote that said he's not sure about it .. is this possible? or is it related to a default alignment that can't be changed?
Thank you,

For every image we can find out its aspect ratio either width/height or height/width.
Assuming that your cell has known width and height you can determine if its going to be too narrow or too short. Moreover you can calculate its new width and height with following formulas:
newWidth = cellheight*oldwidth/oldheight
newHeight = cellwidth*oldheight/oldwidth
CellWidth - NewWidth = 2x PaddingLeft
CellHeight - NewHeight = 2x PaddingTop
So all you need to do now is just divide the result by 2 and cast it onto an integer.
I implemented following getters for each image in database(I am actually pulling these images from sqlite database) in the SubReportProcessing Event for my main report I simply add all my images as DataSource.
public class ImageModel
{
public int ImgId { get; set; }
public byte[] Blob { get; set; }
public string PaddingLeft
{
get
{
var img = byteArrayToImage(Blob);
//cell width and height must be specified in points
//(cellwidth - cellheight * image aspect ratio) / 2
var result = (int)((256.0f - 256.0f * ((float)img.Width / (float)img.Height)) / (float)2) + "pt";
return result;
}
}
public string PaddingTop
{
get
{
var img = byteArrayToImage(Blob);
var result = (int)((256.0f - 256.0f * ((float)img.Height / (float)img.Width)) / (float)2) + "pt";
return result;
}
}
After that operation I can now set padding value under image properties as follows:
=Fields!PaddingLeft.Value
=Fields!PaddingTop.Value
Hope that helps!
Cheers ;)

I'm looking for an answer to this as well; I found this code which does the trick (it works) but it's not very generic (depends on a hard coded page width). With a little work this code could work.

Related

How to dynamically and automatically set FontSize based on view.Width?

"TRYING OUT AUTO SIZING"
Font size too large, so much so part of the string is cut off (when text is too large, a portion is cut off and replaced with ellipsis).
"test text"
Font size too small. The fontSize is a third of its respective view (estimating).
How to set the fontSize of an Element to the size of the Element (and or containing Views) width? Use the examples above as reference - "test text" would take up much more of the view and "TRYING OUT AUTO SIZING" would take up far less.
NOTE: Black boxes denote other elements.
The desired goal is an element (label and or containing view) that when text is changed at run-time, the fontSize is set according to the text assigned and width available to it (this remains constant after build). So that all text is viewable in the string and it uses the width available to it.
Purpose is to support multiple platforms on a variety of devices with widely different scaling.
Whats been tried? NamedSizes based on the idiom (phone/tablet/etc) and manipulating these with multiplication and division based on OS (platform, i.e., IOS, Android, etC). This can't be best practice and there must be a way to go about accomplish this.
Following Xamarin.Forms guide for "fitting text to available size" or "empirically fitting text" yields results that are not as expected.. "CH5: Dealing with sizes"
Please advise on best practice and/or next steps.
Struct
struct FontCalc
{
public FontCalc(Label label, double fontSize, double containerWidth)
: this()
{
// Save the font size.
FontSize = fontSize;
// Recalculate the Label height.
label.FontSize = fontSize;
SizeRequest sizeRequest =
label.Measure(containerWidth, Double.PositiveInfinity);
// Save that height.
TextHeight = sizeRequest.Request.Height;
}
public double FontSize { private set; get; }
public double TextHeight { private set; get; }
}
Implementation
Label label;
public EmpiricalFontSizePage()
{
label = new Label();
Padding = new Thickness(0, Device.RuntimePlatform == Device.iOS ? 30 : 0, 0, 0);
ContentView contentView = new ContentView
{
Content = label
};
contentView.SizeChanged += OnContentViewSizeChanged;
Content = contentView;
}
void OnContentViewSizeChanged(object sender, EventArgs args)
{
// Get View whose size is changing.
View view = (View)sender;
if (view.Width <= 0 || view.Height <= 0)
return;
label.Text =
"This is text displayed. Does it work?";
// Calculate the height of the rendered text.
FontCalc lowerFontCalc = new FontCalc(label, 10, view.Width);
FontCalc upperFontCalc = new FontCalc(label, 100, view.Width);
while (upperFontCalc.FontSize - lowerFontCalc.FontSize > 1)
{
// Get the average font size of the upper and lower bounds.
double fontSize = (lowerFontCalc.FontSize + upperFontCalc.FontSize) / 2;
// Check the new text height against the container height.
FontCalc newFontCalc = new FontCalc(label, fontSize, view.Width);
if (newFontCalc.TextHeight > view.Height)
{
upperFontCalc = newFontCalc;
}
else
{
lowerFontCalc = newFontCalc;
}
}
// Set the final font size and the text with the embedded value.
label.FontSize = lowerFontCalc.FontSize;
label.Text = label.Text.Replace("??", label.FontSize.ToString("F0"));
}
(implementation code from XF docs linked above)
One solution is to use the NuGet package: Forms9Patch
Using its Lines and AutoFit properties we can achieve our desired result. In our case, we want one line and we want our FontSize set to what is required to make our text fit within one line. Lines = 1, AutoFit = Forms9Patch.AutoFit.Width, and FontSize set to a large value (does not matter if it is well over our desired max as setting AutoFit to Width shrinks font till to what is required to make text fit within our specified number of lines) results in a Label that automatically adjusts its FontSize to the maximum space available to it given the text length.

How to create dynamic stopping Scroll Rect in unity?

I have an gameobject1(added Scroll Rect component)and inside of it another gameobject2(The Scroll rect component's content).In gameobject2 has images.The number of images can be 10 or 20..(Any numbers).The Movement Type is Elastic.As you know it will stop scrolling only until gameobject2 height's length. How to stop on dynamic number's of length.In gameobject2 the number of images can be different. It depends on search results. The results can be 5,8, or 200. So I need to scroll until last of search result.So how to stop scrolling on exactly length in Scroll rect component?
You can use ContentSizeFitter component. GameObject with name "Content", is a content for scrollRect component of "ScrollView"-gameObject.
RectTransform#SetSizeWithCurrentAnchors
I use this a lot when building dynamic scrolling lists. After adding all the items I want (and each having a known size, and all positioned using that size) I update the content's RectTransform with the new size (total number of objects added * size of the object).
For example, I have this code:
int i = 0;
//for each item in a list of skills...
IEnumerator<Skill> list = SkillList.getSkillList();
Transform skillListParent = GuiManager.instance.skillPanel.transform;
while(list.MoveNext()) {
Skill sk = list.Current;
//create a prefab clone...
GameObject go = Main.Instantiate(PrefabManager.instance.SKILL_LISTITEM, skillListParent) as GameObject;
//set its position...
go.transform.localPosition = new Vector3(5, i * -110 -5, 5);
//add a button event or other data (some lines omitted)...
Transform t1 = go.transform.FindChild("BuyOne");
t1.GetComponent<Button>().onClick.AddListener(delegate {
doBuySkill(sk);
});
t1.GetChild(0).GetComponent<Text>().text = Main.AsCurrency(sk.getCost(1)) + " pts";
//track how many...
i++;
}
//update rect transform
((RectTransform)skillListParent).SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, (i * 110 + 10));

Is it possible to save a generated image in Codename One?

My question is related to this previous question. What I want to achieve is to stack images (they have transparency), write a string on top, and save the photomontage / photocollage with full resolution.
#Override
protected void beforeMain(Form f) {
Image photoBase = fetchResourceFile().getImage("Voiture_4_3.jpg");
Image watermark = fetchResourceFile().getImage("Watermark.png");
f.setLayout(new LayeredLayout());
final Label drawing = new Label();
f.addComponent(drawing);
// Image mutable dans laquelle on va dessiner (fond blanc)
Image mutableImage = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
drawing.getUnselectedStyle().setBgImage(mutableImage);
drawing.getUnselectedStyle().setBackgroundType(Style.BACKGROUND_IMAGE_SCALED_FIT);
// Paint all the stuff
paints(mutableImage.getGraphics(), photoBase, watermark, photoBase.getWidth(), photoBase.getHeight());
// Save the collage
Image screenshot = Image.createImage(photoBase.getWidth(), photoBase.getHeight());
f.revalidate();
f.setVisible(true);
drawing.paintComponent(screenshot.getGraphics(), true);
String imageFile = FileSystemStorage.getInstance().getAppHomePath() + "screenshot.png";
try(OutputStream os = FileSystemStorage.getInstance().openOutputStream(imageFile)) {
ImageIO.getImageIO().save(screenshot, os, ImageIO.FORMAT_PNG, 1);
} catch(IOException err) {
err.printStackTrace();
}
}
public void paints(Graphics g, Image background, Image watermark, int width, int height) {
g.drawImage(background, 0, 0);
g.drawImage(watermark, 0, 0);
g.setColor(0xFF0000);
// Upper left corner
g.fillRect(0, 0, 10, 10);
// Lower right corner
g.setColor(0x00FF00);
g.fillRect(width - 10, height - 10, 10, 10);
g.setColor(0xFF0000);
Font f = Font.createTrueTypeFont("Geometos", "Geometos.ttf").derive(220, Font.STYLE_BOLD);
g.setFont(f);
// Draw a string right below the M from Mercedes on the car windscreen (measured in Gimp)
g.drawString("HelloWorld",
(int) (848 ),
(int) (610)
);
}
This is the saved screenshot I get if I use the Iphone6 skin (the payload image is smaller than the original one and is centered). If I use the Xoom skin this is what I get (the payload image is still smaller than the original image but it has moved to the left).
So to sum it all up : why is the saved screenshot with Xoom skin different from the one I get with Iphone skin ? Is there anyway to directly save the graphics on which I paint in the paints method so that the saved image would have the original dimensions ?
Thanks a lot to anyone that could help me :-)!
Cheers,
You can save an image in Codename one using the ImageIO class. Notice that you can draw a container hierarchy into a mutable image using the paintComponent(Graphics) method.
You can do both approaches with draw image on mutable or via layouts. Personally I always prefer layouts as I like the abstraction but I wouldn't say the mutable image approach is right/wrong.
Notice that if you change/repaint a lot then mutable images are slower (this will not be noticeable for regular code or on the simulator) as they are forced to use the software renderer and can't use the GPU fully.
In the previous question it seems you placed the image with a "FIT" style which naturally drew it smaller than the containing container and then drew the image on top of it manually... This is problematic.
One solution is to draw everything manually but then you will need to do the "fit" aspect of drawing yourself. If you use layouts you should position everything based on the layouts including your drawing/text.

Finding size of images imported at runtime

I am currently loading images at runtime from directories stored in an XML file, and assigning them to RawImage components via the WWW class. While this is working fine, the image is skewed to fit into the new texture size.
I am wondering how to get an image’s original size or aspect ratio so that I can change the size of the image rect to suit. The images to be imported are at varying sizes and therefore the approach used needs to be responsive to the original size of imported images.
Any suggestions would be much appreciated. [Scripting in uJS]
Many thanks in advance, Ryan
function loadContextImage(texLocation : String)
{
if (!imageView.activeSelf)
{
imageView.SetActive(true);
}
var wwwDirectory = "file://" + texLocation; //this will probably need to change for other OS (PC = file:/ [I think?]) - **REVISE**
var newImgTex = new Texture2D(512, 512);
while(true){
var www : WWW = new WWW(wwwDirectory);
yield www;
www.LoadImageIntoTexture(newImgTex);
if (www.isDone){
break; //if done downloading image break loop
}
}
var imageRender : UI.RawImage = imageView.GetComponent.<RawImage>();
imageRender.texture = newImgTex;
}
If you cannot use an Image (for nay valid reasons), you can get the width and height of the texture:
WWW www = new WWW(url);
yield return www;
Texture2D tex = www.texture;
float aspectRatio = tex.height / tex.width;
rawImage.width = width;
rawImage.height = width * aspectRatio;
This should make the rect of the image of the appropriate ratio of the texture.
If you can use Image and preserveAspectRatio, you get it done by Unity. The result is not necessarily the same since it will keep the dimensions of the box and make the Sprite occupies as much space while keeping ratio.

iTextSharp: align image and text

I am using iTextSharp to export reports in PDF format. Reports' headers should have following format:
The problem is to align report header by center of the page, while there is an image on the left of the page. When I use a table, report header is aligned by center of its cell, not by center of the page. Is there a better approach?
EDIT:
Code for adding header is following:
var doc = new Document(pageSize, margins.Width, margins.Width, margins.Height, margins.Height);
using (PdfWriter.GetInstance(doc, destination))
{
doc.Open();
var headerTable = new PdfPTable(1){ WidthPercentage = 100 };
RenderHeader(headerTable); // adds several lines to headerTable
doc.Add(headerTable);
}
Do you really need a PdfPTable?
Why not add a Paragraph with the data that is right-aligned, followed by a couple of Paragraphs that are centered.
Then add the image at an absolute position, for instance:
Image img = Image.GetInstance(path_to_image);
img.SetAbsolutePosition(36, PdfWriter.getVerticalPosition(true));
document.Add(Image);
Another option is to add the Image in a table or a cell event instead of adding it straight to the table. Suppose that your PdfPTable consists of a single row and a single column, then you could define a cell event like this:
public class ImageCell : IPdfPCellEvent {
public void CellLayout(
PdfPCell cell, Rectangle position, PdfContentByte[] canvases
) {
float x1 = position.Left + 2;
float y1 = position.Top - 2;
float y2 = position.Bottom + 2;
PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
Image img = Image.GetInstance(path_to_image);
img.scaleToFit(10000, y1 - y2);
img.SetAbsolutePosition(x1, y2);
canvas.AddImage(img);
}
}
Suppose that cell is the PdfPCell with the date and the title, then you can do this:
cell.CellEvent = new ImageCell();
Note that in this case, the image will be scaled to the height of the cell.
Forgive me if the code doesn't compile right away, I'm writing this by heart (based on experience), I didn't test the actual code.

Resources