I grabbed the following code from another site - I can't find a problem with it but it keeps giving me a nullpointerexception. The issue I think is right in the first part before the setContentView but including the whole thing just in case. Thanks in advance for the help!
public class TileSet extends Activity {
Bitmap originalImage = BitmapFactory.decodeResource(getResources(),
R.drawable.announcementbc);
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Create an Image view and add our bitmap with reflection to it
imageView.setImageBitmap(getRefelection(originalImage));
//imageView.setImageBitmap(image);
//Add the image to a linear layout and display it
LinearLayout linLayout = new LinearLayout(this);
linLayout.addView(imageView, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// set LinearLayout as ContentView
setContentView(linLayout);
}
// public static Bitmap getRefelection(Bitmap image)
public static Bitmap getRefelection(Bitmap image)
{
//The gap we want between the reflection and the original image
final int reflectionGap = 4;
//Get you bit map from drawable folder
Bitmap originalImage = image;
int width = originalImage.getWidth();
int height = originalImage.getHeight();
//This will not scale but will flip on the Y axis
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
//Create a Bitmap with the flip matix applied to it.
//We only want the bottom half of the image
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);
//Create a new bitmap with same width but taller to fit reflection
Bitmap bitmapWithReflection = Bitmap.createBitmap(width
, (height + height/2), Config.ARGB_8888);
//Create a new Canvas with the bitmap that's big enough for
//the image plus gap plus reflection
Canvas canvas = new Canvas(bitmapWithReflection);
//Draw in the original image
canvas.drawBitmap(originalImage, 0, 0, null);
//Draw in the gap
Paint deafaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
//Draw in the reflection
canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);
//Create a shader that is a linear gradient that covers the reflection
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
TileMode.CLAMP);
//Set the paint to use this shader (linear gradient)
paint.setShader(shader);
//Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
//Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);
reflectionImage.recycle();
return bitmapWithReflection;
}
}
imageView.setImageBitmap(getRefelection(originalImage));
This is the line it is crashing on, and the reason is that imageView is null.
When you create a member variable such as the one you listed, you need to either create an object for it to point to, or set it to an already-created object.
In your case, I'm guessing you want to set it to one already created by your layout. Your layout XML should have some ImageView declared, but in order to get it in the Java code, you'll need to call findViewById()
If your XML is declared like this, with an id:
<ImageView
android:id="#+id/my_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
Then you'll need to write the following before you can call setImageBitmap():
imageView = (ImageView) findViewById(R.id.my_image_view);
Additionally, you cannot make the findViewById call until after you make the call to setContentView(), because that's the call that actually creates your ImageView.
Although, looking at your code a bit further, you probably don't need to do the reflection bit, or even the setImageBitmap() call, because you can specify the drawable directly in the XML (unless you want to change it when the program is running):
<ImageView
android:id="#+id/my_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/announcementbc"
/>
By adding the source line, and pointing it to your drawable, the setContentView call will automatically set the correct Bitmap on the ImageView.
Here is the latest failed code as per the comment above
public class Tile2 extends Activity{
// Bitmap originalImage = BitmapFactory.decodeResource(getResources(), R.drawable.announcementbc);
ImageView imageView;
Bitmap originalImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView (R.layout.tile);
imageView = (ImageView) findViewById(R.id.ivTile);
originalImage = BitmapFactory.decodeResource(getResources(), R.drawable.announcementbc);
// ImageView imageView = new ImageView(this);
imageView.setImageBitmap(getReflection(originalImage));
//Add the image to a linear layout and display it
LinearLayout linLayout = new LinearLayout(this);
linLayout.addView(imageView, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// set LinearLayout as ContentView
setContentView(linLayout);
}
public static Bitmap getReflection(Bitmap image)
{
//The gap we want between the reflection and the original image
final int reflectionGap = 4;
//Get you bit map from drawable folder
Bitmap originalImage = image;
int width = originalImage.getWidth();
int height = originalImage.getHeight();
//This will not scale but will flip on the Y axis
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
//Create a Bitmap with the flip matix applied to it.
//We only want the bottom half of the image
Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);
//Create a new bitmap with same width but taller to fit reflection
Bitmap bitmapWithReflection = Bitmap.createBitmap(width
, (height + height/2), Config.ARGB_8888);
//Create a new Canvas with the bitmap that's big enough for
//the image plus gap plus reflection
Canvas canvas = new Canvas(bitmapWithReflection);
//Draw in the original image
canvas.drawBitmap(originalImage, 0, 0, null);
//Draw in the gap
Paint deafaultPaint = new Paint();
canvas.drawRect(0, height, width, height + reflectionGap, deafaultPaint);
//Draw in the reflection
canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);
//Create a shader that is a linear gradient that covers the reflection
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
TileMode.CLAMP);
//Set the paint to use this shader (linear gradient)
paint.setShader(shader);
//Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
//Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, height, width,
bitmapWithReflection.getHeight() + reflectionGap, paint);
reflectionImage.recycle();
return bitmapWithReflection;
}
}
Related
I'm stuck on full scaling for my JavaFX application. I'm in the process of making a full screen feature for the application and I'm running into issues on trying to get the aspect ratio and positioning right without manually editing the values.
With the way I've been trying, the values butcher the game's start screen making the positioning change making the designs of the game offset from the center of the application. I can understand the reasoning behind it with the way I set it up. My problem is wondering how to scale the start screen and keep it's original position without having to manually edit the values.
What I thought of was trying to input the value and having it scale according to that value then putting the result in the position of objects X and Y.
if (fullscreen) {
WIDTH = (Enter aspect ratio here) * 1.5;
HEIGHT = (Enter aspect ratio here) * 1.5;
} else {
WIDTH = 990;
HEIGHT = 525;
}
with Obvious flaws this butchers the start screen.
My solution was to make a double() that you just enter the value of the application WIDTH/HEIGHT then entering the amount you want to divide by (since I couldn't come up with exact cords, I grabbed the WIDTH and divided by specific value for it to align in the center) following with a boolean to state whether it's full screened or not. Though my only issue with this theory is that it'll only work with 1920x1080 monitors so I'd assume I would have to manually enter all types of aspect ratios to make it fit otherwise the start screen would be butchered.
I've seen a way of scaling here:
JavaFX fullscreen - resizing elements based upon screen size
Though I'm not sure how to correctly implement it.
public static boolean fullscreen = false;
public static double WIDTH = 990;
public static double HEIGHT = 525;
public static Pane pane = new Pane();
public static void StartScreen() {
pane.setPrefSize(WIDTH, (HEIGHT - 25)); // the 25 is for the text field/input.
pane.setStyle("-fx-background-color: transparent;");
Group sGroup = new Group();
Image i = new Image("file:start/So7AA.png");
ImageView outer = new ImageView(i);
// outer.setX(Ce.WIDTH/4.75); //4.75 // The functioning code for the snippit
// outer.setY(-10); //-10
outer.setX(Ce.WIDTH/position(3.60, fullscreen)); //4.75 // The non functioning code.
outer.setY(position(-1, Ce.fullscreen)); //-10
outer.setFitWidth(550);
outer.setFitHeight(550);
outer.setOpacity(.3);
GaussianBlur gBlur = new GaussianBlur();
gBlur.setRadius(50);
ImageView seal = new ImageView(i);
// seal.setX(Ce.WIDTH/3.83); //247.5 - 3.83
// seal.setY(39); //39
seal.setX(Ce.WIDTH/position(3.83, fullscreen)); //247.5 - 3.83
seal.setY(position(32, Ce.fullscreen)); //39
seal.setFitWidth(450);
seal.setFitHeight(450);
ImageView sealBlur = new ImageView(i);
// sealBlur.setX(Ce.WIDTH/3.83); //247.5 - 3.83
// sealBlur.setY(39); //39
sealBlur.setX(Ce.WIDTH/position(3.83, fullscreen)); //247.5 - 3.83
sealBlur.setY(position(32, Ce.fullscreen));
sealBlur.setFitWidth(450);
sealBlur.setFitHeight(450);
sealBlur.setEffect(gBlur);
}
For getting the values of the WIDTH and HEIGHT:
public static double getWidth(double W, boolean fs) {
if (fs) {
return WIDTH = Screen.getPrimary().getBounds().getMaxX();
} else {
return WIDTH = W;
}
}
public static double getHeight(double H, boolean fs) {
if (fs) {
return HEIGHT = Screen.getPrimary().getBounds().getMaxY();
} else {
return HEIGHT = H;
}
}
I know there's a way around this, I'm just not sure how to pull it off.
I'm not sure exactly what the requirements are here, but it looks like you have three images, which you want centered, and you want them all scaled by the same amount so that one of the images fills the available space in its container. (Then, you just need to make sure its container grows to fill all the space, and you can call stage.setFullScreen(true) or stage.setMaximized(true) as needed.)
You can do this with a pretty simple custom pane that manages the layout in the layoutChildren() method:
public class ImagePane extends Region {
private final Image image1;
private final ImageView imageView1;
private final Image image2;
private final ImageView imageView2;
private final Image image3;
private final ImageView imageView3;
public ImagePane(Image image1, Image image2, Image image3) {
this.image1 = image1;
this.image2 = image2;
this.image3 = image3;
imageView1 = new ImageView(image1);
imageView2 = new ImageView(image2);
imageView3 = new ImageView(image3);
getChildren().addAll(imageView1, imageView2, imageView3);
}
#Override
protected void layoutChildren() {
double xScale = getWidth() / image1.getWidth();
double yScale = getHeight() / image1.getHeight();
double scale = Math.min(xScale, yScale);
for (ImageView view : List.of(imageView1, imageView2, imageView3) {
scaleAndCenter(view, scale);
}
}
private void scaleAndCenter(ImageView view, scale) {
double w = scale * view.getImage().getWidth();
double h = scale * view.getImage().getHeight();
view.setFitWidth(w);
view.setFitHeight(h);
view.relocate((getWidth()-w) / 2, (getHeight()-h) / 2);
}
}
The rest of your layout looks something like:
Label label = new Label("Type in 'start'.\nType in 'options' for options.\n(Demo)");
TextField textField = new TextField();
ImagePane imagePane = new ImagePane(new Image(...), new Image(...), new Image(...));
AnchorPane anchor = new AnchorPane(imagePane, label);
AnchorPane.setTopAnchor(imagePane, 0.0);
AnchorPane.setRightAnchor(imagePane, 0.0);
AnchorPane.setBottomAnchor(imagePane, 0.0);
AnchorPane.setLeftAnchor(imagePane, 0.0);
AnchorPane.setTopAnchor(label, 5.0);
AnchorPane.setLeftAnchor(label, 5.0);
BorderPane root = new BorderPane();
root.setCenter(anchor);
root.setBottom(textField);
Now everything should just respond to whatever size is assigned to the root pane, so setting full screen mode should "just work".
I have a sample 3D application (built by taking reference from the Javafx sample 3DViewer) which has a table created by laying out Boxes and Panes:
The table is centered wrt (0,0,0) coordinates and camera is at -z position initially.
It has the zoom-in/out based on the camera z position from the object.
On zooming in/out the object's boundsInParent increases/decreases i.e. area of the face increases/decreases. So the idea is to put more text when we have more area (always confining within the face) and lesser text or no text when the face area is too less. I am able to to do that using this node hierarchy:
and resizing the Pane (and managing the vBox and number of texts in it) as per Box on each zoom-in/out.
Now the issue is that table boundsInParent is giving incorrect results (table image showing the boundingBox off at the top) whenever a text is added to the vBox for the first time only. On further zooming-in/out gives correct boundingBox and does not go off.
Below is the UIpane3D class:
public class UIPane3D extends Pane
{
VBox textPane;
ArrayList<String> infoTextKeys = new ArrayList<>();
ArrayList<Text> infoTextValues = new ArrayList<>();
Rectangle bgCanvasRect = null;
final double fontSize = 16.0;
public UIPane3D() {
setMouseTransparent(true);
textPane = new VBox(2.0)
}
public void updateContent() {
textPane.getChildren().clear();
getChildren().clear();
for (Text textNode : infoTextValues) {
textPane.getChildren().add(textNode);
textPane.autosize();
if (textPane.getHeight() > getHeight()) {
textPane.getChildren().remove(textNode);
textPane.autosize();
break;
}
}
textPane.setTranslateY(getHeight() / 2 - textPane.getHeight() / 2.0);
bgCanvasRect = new Rectangle(getWidth(), getHeight());
bgCanvasRect.setFill(Color.web(Color.BURLYWOOD.toString(), 0.10));
bgCanvasRect.setVisible(true);
getChildren().addAll(bgCanvasRect, textPane);
}
public void resetInfoTextMap()
{
if (infoTextKeys != null || infoTextValues != null)
{
try
{
infoTextKeys.clear();
infoTextValues.clear();
} catch (Exception e){e.printStackTrace();}
}
}
public void updateInfoTextMap(String pKey, String pValue)
{
int index = -1;
boolean objectFound = false;
for (String string : infoTextKeys)
{
index++;
if(string.equals(pKey))
{
objectFound = true;
break;
}
}
if(objectFound)
{
infoTextValues.get(index).setText(pValue.toUpperCase());
}
else
{
if (pValue != null)
{
Text textNode = new Text(pValue.toUpperCase());
textNode.setFont(Font.font("Consolas", FontWeight.BLACK, FontPosture.REGULAR, fontSize));
textNode.wrappingWidthProperty().bind(widthProperty());
textNode.setTextAlignment(TextAlignment.CENTER);
infoTextKeys.add(pKey);
infoTextValues.add(textNode);
}
}
}
}
The code which get called at the last after all the manipulations:
public void refreshBoundingBox()
{
if(boundingBox != null)
{
root3D.getChildren().remove(boundingBox);
}
PhongMaterial blueMaterial = new PhongMaterial();
blueMaterial.setDiffuseColor(Color.web(Color.CRIMSON.toString(), 0.25));
Bounds tableBounds = table.getBoundsInParent();
boundingBox = new Box(tableBounds.getWidth(), tableBounds.getHeight(), tableBounds.getDepth());
boundingBox.setMaterial(blueMaterial);
boundingBox.setTranslateX(tableBounds.getMinX() + tableBounds.getWidth()/2.0);
boundingBox.setTranslateY(tableBounds.getMinY() + tableBounds.getHeight()/2.0);
boundingBox.setTranslateZ(tableBounds.getMinZ() + tableBounds.getDepth()/2.0);
boundingBox.setMouseTransparent(true);
root3D.getChildren().add(boundingBox);
}
Two things:
The table3D's boundsInParent is not updated properly when texts are added for the first time.
What would be the right way of putting texts on 3D nodes? I am having to manipulate a whole lot to bring the texts as required.
Sharing code here.
For the first question, about the "jump" that can be noticed just when after scrolling a new text item is laid out:
After digging into the code, I noticed that the UIPane3D has a VBox textPane that contains the different Text nodes. Every time updateContent is called, it tries to add a text node, but it checks that the vbox's height is always lower than the pane's height, or else the node will be removed:
for (Text textNode : infoTextValues) {
textPane.getChildren().add(textNode);
textPane.autosize();
if (textPane.getHeight() > getHeight()) {
textPane.getChildren().remove(textNode);
textPane.autosize();
break;
}
}
While this is basically correct, when you add a node to the scene, you can't get textPane.getHeight() immediately, as it hasn't been laid out yet, and you have to wait until the next pulse. This is why the next time you scroll, the height is correct and the bounding box is well placed.
One way to force the layout and get the correct height of the textNode is by forcing css and a layout pass:
for (Text textNode : infoTextValues) {
textPane.getChildren().add(textNode);
// force css and layout
textPane.applyCss();
textPane.layout();
textPane.autosize();
if (textPane.getHeight() > getHeight()) {
textPane.getChildren().remove(textNode);
textPane.autosize();
break;
}
}
Note that:
This method [applyCss] does not normally need to be invoked directly but may be used in conjunction with Parent.layout() to size a Node before the next pulse, or if the Scene is not in a Stage.
For the second question, about a different solution to add Text to 3D Shape.
Indeed, placing a (2D) text on top of a 3D shape is quite difficult, and requires complex maths (that are done quite nicely in the project, by the way).
There is an alternative avoiding the use of 2D nodes directly.
Precisely in a previous question, I "wrote" into an image, that later on I used as the material diffuse map of a 3D shape.
The built-in 3D Box places the same image into every face, so that wouldn't work. We can implement a 3D prism, or we can make use of the CuboidMesh node from the FXyz3D library.
Replacing the Box in UIPaneBoxGroup:
final CuboidMesh contentShape;
UIPane3D displaypane = null;
PhongMaterial shader = new PhongMaterial();
final Color pColor;
public UIPaneBoxGroup(final double pWidth, final double pHeight, final double pDepth, final Color pColor) {
contentShape = new CuboidMesh(pWidth, pHeight, pDepth);
this.pColor = pColor;
contentShape.setMaterial(shader);
getChildren().add(contentShape);
addInfoUIPane();
}
and adding the generateNet method:
private Image generateNet(String string) {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
Label label5 = new Label(string);
label5.setFont(Font.font("Consolas", FontWeight.BLACK, FontPosture.REGULAR, 40));
GridPane.setHalignment(label5, HPos.CENTER);
grid.add(label5, 3, 1);
double w = contentShape.getWidth() * 10; // more resolution
double h = contentShape.getHeight() * 10;
double d = contentShape.getDepth() * 10;
final double W = 2 * d + 2 * w;
final double H = 2 * d + h;
ColumnConstraints col1 = new ColumnConstraints();
col1.setPercentWidth(d * 100 / W);
ColumnConstraints col2 = new ColumnConstraints();
col2.setPercentWidth(w * 100 / W);
ColumnConstraints col3 = new ColumnConstraints();
col3.setPercentWidth(d * 100 / W);
ColumnConstraints col4 = new ColumnConstraints();
col4.setPercentWidth(w * 100 / W);
grid.getColumnConstraints().addAll(col1, col2, col3, col4);
RowConstraints row1 = new RowConstraints();
row1.setPercentHeight(d * 100 / H);
RowConstraints row2 = new RowConstraints();
row2.setPercentHeight(h * 100 / H);
RowConstraints row3 = new RowConstraints();
row3.setPercentHeight(d * 100 / H);
grid.getRowConstraints().addAll(row1, row2, row3);
grid.setPrefSize(W, H);
grid.setBackground(new Background(new BackgroundFill(pColor, CornerRadii.EMPTY, Insets.EMPTY)));
new Scene(grid);
return grid.snapshot(null, null);
}
Now all the 2D related code can be removed (including displaypane), and after a scrolling event get the image:
public void refreshBomUIPane() {
Image net = generateNet(displaypane.getText());
shader.setDiffuseMap(net);
}
where in UIPane3D:
public String getText() {
return infoTextKeys.stream().collect(Collectors.joining("\n"));
}
I've also removed the bounding box to get this picture:
I haven't played around with the number of text nodes that can be added to the VBox, the font size nor with an strategy to avoid generating images on every scroll: only when the text changes this should be done. So with the current approach is quite slow, but it can be improved notably as there are only three possible images for each box.
IO Exception Thrown (The process cannot access the file 'filename' because it is being used by a...
I am Unable To Delete Image File From My Server Path It Gaves Error That The Process Cannot Access The File "FileName" Because it is being Used By Another Process. I Tried Many Methods But Still All In Vain. Please Help me Out in This Issue.
Here is My Code Snippet.
using System;
using System.Data;
using System.Web;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Web.Security;
using System.Text;
using System.DirectoryServices;
using System.Collections;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
//============ Main Block =================
watermark();
DeleteImages();
\\ Here is My Delete Method That I Call To Delete The Images
//===== ==== My Delete Method To Delete Files==================
public void DeleteImages()
{
try
{
File.Delete(Server.MapPath(".\\TmpImages\\WaterMark.jpg")); \\This Image Deleted Fine.
File.Delete(Server.MapPath(".\\TmpImages\\SavedImage.jpg")); \\ Exception Thrown On Deleting of This Image.
}
catch (Exception ex)
{
LogManager.LogException(ex, "Error in Deleting Images.");
Master.ShowMessage(ex.Message, true);
}
}
\ ==== Method Declartion That Make Watermark of One Image On Another Image.=======
public void watermark()
{
//create a image object containing the photograph to watermark
Image imgPhoto = Image.FromFile(Server.MapPath(".\\TmpImages\\SavedImage.jpg"));
int phWidth = imgPhoto.Width;
int phHeight = imgPhoto.Height;
//create a Bitmap the Size of the original photograph
Bitmap bmPhoto = new Bitmap(phWidth, phHeight, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//load the Bitmap into a Graphics object
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//create a image object containing the watermark
Image imgWatermark = new Bitmap(Server.MapPath(".\\TmpImages\\PrintasWatermark.jpg"));
int wmWidth = imgWatermark.Width;
int wmHeight = imgWatermark.Height;
//Set the rendering quality for this Graphics object
grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
//Draws the photo Image object at original size to the graphics object.
grPhoto.DrawImage(
imgPhoto, // Photo Image object
new Rectangle(0, 0, phWidth, phHeight), // Rectangle structure
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
phWidth, // Width of the portion of the source image to draw.
phHeight, // Height of the portion of the source image to draw.
GraphicsUnit.Pixel); // Units of measure
//-------------------------------------------------------
//to maximize the size of the Copyright message we will
//test multiple Font sizes to determine the largest posible
//font we can use for the width of the Photograph
//define an array of point sizes you would like to consider as possiblities
//-------------------------------------------------------
//Define the text layout by setting the text alignment to centered
StringFormat StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Center;
//define a Brush which is semi trasparent black (Alpha set to 153)
SolidBrush semiTransBrush2 = new SolidBrush(Color.FromArgb(153, 0, 0, 0));
//define a Brush which is semi trasparent white (Alpha set to 153)
SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(153, 255, 255, 255));
//------------------------------------------------------------
//Step #2 - Insert Watermark image
//------------------------------------------------------------
//Create a Bitmap based on the previously modified photograph Bitmap
Bitmap bmWatermark = new Bitmap(bmPhoto);
bmWatermark.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
//Load this Bitmap into a new Graphic Object
Graphics grWatermark = Graphics.FromImage(bmWatermark);
//To achieve a transulcent watermark we will apply (2) color
//manipulations by defineing a ImageAttributes object and
//seting (2) of its properties.
ImageAttributes imageAttributes = new ImageAttributes();
//The first step in manipulating the watermark image is to replace
//the background color with one that is trasparent (Alpha=0, R=0, G=0, B=0)
//to do this we will use a Colormap and use this to define a RemapTable
ColorMap colorMap = new ColorMap();
//My watermark was defined with a background of 100% Green this will
//be the color we search for and replace with transparency
colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
ColorMap[] remapTable = { colorMap };
imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);
//The second color manipulation is used to change the opacity of the
//watermark. This is done by applying a 5x5 matrix that contains the
//coordinates for the RGBA space. By setting the 3rd row and 3rd column
//to 0.3f we achive a level of opacity
float[][] colorMatrixElements = {
new float[] {1.0f, 0.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 1.0f, 0.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 1.0f, 0.0f, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, 0.3f, 0.0f},
new float[] {0.0f, 0.0f, 0.0f, 0.0f, 1.0f}};
ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
imageAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default,
ColorAdjustType.Bitmap);
//For this example we will place the watermark in the upper right
//hand corner of the photograph. offset down 10 pixels and to the
//left 10 pixles
int xPosOfWm = ((phWidth - wmWidth) - 10);
int yPosOfWm = 10;
grWatermark.DrawImage(imgWatermark,
new Rectangle(xPosOfWm, yPosOfWm, wmWidth, wmHeight), //Set the detination Position
0, // x-coordinate of the portion of the source image to draw.
0, // y-coordinate of the portion of the source image to draw.
wmWidth, // Watermark Width
wmHeight, // Watermark Height
GraphicsUnit.Pixel, // Unit of measurment
imageAttributes); //ImageAttributes Object
//Replace the original photgraphs bitmap with the new Bitmap
imgPhoto = bmWatermark;
grPhoto.Dispose();
grWatermark.Dispose();
//save new image to file system.
imgPhoto.Save(Server.MapPath(".\\TmpImages\\WaterMark.jpg"), ImageFormat.Jpeg);
imgPhoto.Dispose();
imgWatermark.Dispose();
}
Don't just load the image - the documentation does say that the file or stream must be available for the duration of the Image instance.
Instead, load it from the file, create a new image from it, and then dispose the original:
Image imgPhoto = GetCopyImage(Server.MapPath(".\TmpImages\SavedImage.jpg"));
...
private Image GetCopyImage(string path)
{
using (Image im = Image.FromFile(path))
{
Bitmap bm = new Bitmap(im);
return bm;
}
}
If you just load it, then the image reference will hold the file open until it is Disposed - which may not happen until the application is closed.
I want to currently work on Canvas in HTML5. I am new to canvas and want to start working on it. I am using easeljs for implementing canvas. But can anybody specify any particular .js file to implement Canvas. As when I am using this .js I am getting error : "0x800a1391 - Microsoft JScript runtime error: 'Stage' is undefined If there is a handler for this exception, the program may be safely continued."
Here my piece of code where we getting the above specified error. I have copied this code from internet only:
<script>
//EaselJS Stage instance that wraps the Canvas element
var stage;
//EaselJS Shape instance that we will animate
var circle;
//radius of the circle Graphics that we will draw.
var CIRCLE_RADIUS = 10;
//x position that we will reset Shape to when it goes off
//screen
var circleXReset;
//EaselJS Rectangle instance we will use to store the bounds
//of the Canvas
var bounds;
//initialize function, called when page loads.
function init() {
//check and see if the canvas element is supported in
//the current browser
////http://diveintohtml5.org/detect.html#canvas
if (!(!!document.createElement('canvas').getContext)) {
var wrapper = document.getElementById("canvasWrapper");
wrapper.innerHTML = "Your browser does not appear to support " +
"the HTML5 Canvas element";
return;
}
//get a reference to the canvas element
var canvas = document.getElementById("stageCanvas");
//copy the canvas bounds to the bounds instance.
//Note, if we resize the canvas, we need to reset
//these bounds.
//bounds = new Rectangle();
//bounds.width = canvas.width;
//bounds.height = canvas.height;
//pass the canvas element to the EaselJS Stage instance
//The Stage class abstracts away the Canvas element and
//is the root level display container for display elements.
stage = new Stage(canvas);
//Create an EaselJS Graphics element to create the
//commands to draw a circle
var g = new Graphics();
//stroke of 1 px
g.setStrokeStyle(1);
//Set the stroke color, using the EaselJS
//Graphics.getRGB static method.
//This creates a white color, with an alpha
//of .7
g.beginStroke(Graphics.getRGB(255, 255, 255, .7));
//draw the circle
g.drawCircle(0, 0, CIRCLE_RADIUS);
//note that the circle has not been drawn yet.
//the Graphics instance just has the commands to
//draw the circle.
//It will be drawn when the stage needs to render it
//which is usually when we call stage.tick()
//create a new Shape instance. This is a DisplayObject
//which can be added directly to the stage (and rendered).
//Pass in the Graphics instance that we created, and that
//we want the Shape to draw.
circle = new Shape(g);
//set the initial x position, and the reset position
circle.x = circleXReset = -CIRCLE_RADIUS;
//set the y position
circle.y = canvas.height / 2;
//add the circle to the stage.
stage.addChild(circle);
//tell the stage to render to the canvas
stage.update();
Ticker.setFPS(24);
//Subscribe to the Tick class. This will call the tick
//method at a set interval (similar to ENTER_FRAME with
//the Flash Player)
Ticker.addListener(this);
}
//function called by the Tick instance at a set interval
function tick() {
//check and see if the Shape has gone of the right
//of the stage.
if (circle.x > bounds.width) {
//if it has, reset it.
circle.x = circleXReset;
}
//move the circle over 10 pixels
circle.x += 8;
//re-render the stage
stage.update();
}
</script>
The only thing in the above code is just to add "createjs" before every even.
<script>
//EaselJS Stage instance that wraps the Canvas element
var stage;
//EaselJS Shape instance that we will animate
var circle;
//radius of the circle Graphics that we will draw.
var CIRCLE_RADIUS = 10;
//x position that we will reset Shape to when it goes off
//screen
var circleXReset;
//EaselJS Rectangle instance we will use to store the bounds
//of the Canvas
var bounds;
//initialize function, called when page loads.
function init() {
//check and see if the canvas element is supported in
//the current browser
////http://diveintohtml5.org/detect.html#canvas
if (!(!!document.createElement('canvas').getContext)) {
var wrapper = document.getElementById("canvasWrapper");
wrapper.innerHTML = "Your browser does not appear to support " +
"the HTML5 Canvas element";
return;
}
//get a reference to the canvas element
var canvas = document.getElementById("stageCanvas");
//copy the canvas bounds to the bounds instance.
//Note, if we resize the canvas, we need to reset
//these bounds.
//var s = new Shape();
//s.graphics.setStrokeStyle(1).beginStroke("#f00").drawRect(0, 0, canvas.width, canvas.height);
//stage.addChild(s);
bounds = new **createjs**.Rectangle();
bounds.width = canvas.width;
bounds.height = canvas.height;
//pass the canvas element to the EaselJS Stage instance
//The Stage class abstracts away the Canvas element and
//is the root level display container for display elements.
stage = new createjs.Stage(canvas);
//Create an EaselJS Graphics element to create the
//commands to draw a circle
var g = new **createjs**.Graphics();
//stroke of 1 px
g.setStrokeStyle(1);
//Set the stroke color, using the EaselJS
//Graphics.getRGB static method.
//This creates a white color, with an alpha
//of .7
g.beginStroke(createjs.Graphics.getRGB(255, 255, 255, .7));
//draw the circle
g.drawCircle(0, 0, CIRCLE_RADIUS);
//note that the circle has not been drawn yet.
//the Graphics instance just has the commands to
//draw the circle.
//It will be drawn when the stage needs to render it
//which is usually when we call stage.tick()
//create a new Shape instance. This is a DisplayObject
//which can be added directly to the stage (and rendered).
//Pass in the Graphics instance that we created, and that
//we want the Shape to draw.
circle = new createjs.Shape(g);
//set the initial x position, and the reset position
circle.x = circleXReset = -CIRCLE_RADIUS;
//set the y position
circle.y = canvas.height / 2;
//add the circle to the stage.
stage.addChild(circle);
//tell the stage to render to the canvas
stage.update();
createjs.Ticker.setFPS(24);
//Subscribe to the Tick class. This will call the tick
//method at a set interval (similar to ENTER_FRAME with
//the Flash Player)
createjs.Ticker.addListener(this);
}
//function called by the Tick instance at a set interval
function tick() {
//check and see if the Shape has gone of the right
//of the stage.
if (circle.x > bounds.width) {
//if it has, reset it.
circle.x = circleXReset;
}
//move the circle over 10 pixels
circle.x += 8;
//re-render the stage
stage.update();
}
</script>
I have marked as bold what we have to add before every function or event.
This is about as basic as it gets. I don't want to use an image file. Rather, I want to programmatically draw a circle and blit it to a surface (as they say in pygame).
I tried to follow the "Using CanvasLayers" example here:
https://developers.google.com/playn/devguide/rendering
From my game class:
// Surface
SurfaceLayer surface;
// Background
int width = 640;
int height = 480;
//ImageLayer bgLayer;
CanvasImage bgImage;
Canvas canvas;
// Circle
CanvasImage circleImage;
//ImageLayer circleLayer;
int circleRadius = 20;
int circleX = 0;
int circleY = 0;
#Override
public void init() {
// create a surface
surface = graphics().createSurfaceLayer(width, height);
graphics().rootLayer().add(surface);
// create a solid background
// http://code.google.com/p/playn101/source/browse/core/src/main/java/playn101/core/J.java#81
bgImage = graphics().createImage(width, height);
canvas = bgImage.canvas();
canvas.setFillColor(0xff87ceeb);
canvas.fillRect(0, 0, width, height);
//bgLayer = graphics().createImageLayer(bgImage);
//graphics().rootLayer().add(bgLayer);
// create a circle
circleImage = graphics().createImage(circleRadius, circleRadius);
canvas = circleImage.canvas();
canvas.setFillColor(0xff0000eb);
canvas.fillCircle(circleX, circleY, circleRadius);
//circleLayer = graphics().createImageLayer(circleImage);
//graphics().rootLayer().add(circleLayer);
}
#Override
public void paint(float alpha) {
// the background automatically paints itself, so no need to do anything
// here!
surface.clear(0);
surface.drawImage(bgImage, 0, 0);
surface.drawImage(circleImage, 100, 100);
}
But I get a blank window in Java and Eclipse complains:
The method drawImage(CanvasImage, int, int) is undefined for the type
SurfaceLayer
That, however, is the way it is used in the example at the link.
If the code you provided even compiles, then you are using some very old version of PlayN.
Update to PlayN 1.1.1 and fix the compilation errors that result, and your code will work fine.
The following is your code updated to work with PlayN 1.1.1:
private SurfaceLayer surface;
private CanvasImage bgImage;
private CanvasImage circleImage;
#Override
public void init() {
// create a surface
int width = graphics().width(), height = graphics().height();
surface = graphics().createSurfaceLayer(width, height);
graphics().rootLayer().add(surface);
// create a solid background
bgImage = graphics().createImage(width, height);
Canvas canvas = bgImage.canvas();
canvas.setFillColor(0xff87ceeb);
canvas.fillRect(0, 0, width, height);
// create a circle
int circleRadius = 20;
int circleX = 0;
int circleY = 0;
circleImage = graphics().createImage(circleRadius, circleRadius);
canvas = circleImage.canvas();
canvas.setFillColor(0xff0000eb);
canvas.fillCircle(circleX, circleY, circleRadius);
}
#Override
public void paint(float alpha) {
Surface s = surface.surface();
s.clear();
s.drawImage(bgImage, 0, 0);
s.drawImage(circleImage, 100, 100);
}
If you really intend to make a game using this approach, you should use ImmediateLayer not SurfaceLayer. ImmediateLayer will issue your drawImage, etc. calls directly against the framebuffer. SurfaceLayer will make an off-screen framebuffer and render everything into that and then copy that off-screen framebuffer to the main framebuffer every frame (in addition to the double buffering naturally performed by OpenGL, etc.), resulting in a needless copy of your entire screen.
Your code looks fine to me...
set the canvasTransform,
canvas.setTransform(1, 0, 0, 1, 0, 0);
and please for testing purposes make the bg bigger
graphics().createImage(circleRadius, circleRadius); (400,400)