Hi all,
I'm trying to have transparent PNGs on my screen.
What is the best way to doing this ? I'm in C#, I tried DirectX, but it doesn't work.
What am I doing wrong ?
My code :
Code:
using System;
using System.Drawing;
using System.Windows.Forms;
using Microsoft.WindowsMobile.DirectX;
using Microsoft.WindowsMobile.DirectX.Direct3D;
using System.Runtime.InteropServices;
namespace Microsoft.Samples.MD3DM
{
// The main class for this sample
public class SimpleSMS : Form
{
// Our global variables for this project
Device device = null;
Texture texture = null;
Sprite sprite = null;
Rectangle rect;
public SimpleSMS()
{
// Set the caption
this.Text = "SimpleSMS";
this.MinimizeBox = false;
}
// Prepare the rendering device
public bool InitializeGraphics()
{
try
{
// Now let's setup our D3D parameters
PresentParameters presentParams = new PresentParameters();
presentParams.Windowed = true;
presentParams.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Default, this, CreateFlags.None, presentParams);
this.OnCreateDevice(device, null);
}
catch (DirectXException)
{
return false;
}
return true;
}
void OnCreateDevice(object sender, EventArgs e)
{
texture = TextureLoader.FromFile(device, @"badge.png");
sprite = new Sprite(device);
rect = new Rectangle(0, 0, 48, 48);
}
// All rendering for each frame occurs here
private void Render()
{
if (device != null)
{
device.Clear(ClearFlags.Target, System.Drawing.Color.Black, 1.0f, 0);
//Begin the scene
device.BeginScene();
device.RenderState.SourceBlend = Blend.SourceAlpha;
device.RenderState.DestinationBlend = Blend.InvSourceAlpha;
device.RenderState.AlphaBlendEnable = true;
sprite.Begin(SpriteFlags.AlphaBlend);
sprite.Draw(texture, rect, new Vector3(0.0f, 0.0f, 0.0f), new Vector3(100.0f, 100.0f, 0.0f), Color.White.ToArgb());
sprite.End();
//End the scene
device.EndScene();
device.Present();
}
}
// Called to repaint the window
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
// Render on painting
this.Render();
// Render again
this.Invalidate();
}
// Called to repaint the window background
protected override void OnPaintBackground(
System.Windows.Forms.PaintEventArgs e)
{
// Do nothing to ensure that the rendering area is not overdrawn
}
// Close the window when Esc is pressed
protected override void OnKeyPress(
System.Windows.Forms.KeyPressEventArgs e)
{
// Esc was pressed
if ((int)(byte)e.KeyChar == (int)System.Windows.Forms.Keys.Escape)
this.Close();
}
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
SimpleSMS frm = new SimpleSMS();
// Initialize Direct3D
if (!frm.InitializeGraphics())
{
MessageBox.Show("Could not initialize Direct3D. " +
"This tutorial will exit.");
return;
}
Application.Run(frm);
}
}
}
Thanks for answers,
Scuse my bad english :-/
Not sure this helps, but RLTODAY works very well with transparent pngs in any WM version, and recently he released the source code:
http://rotlaus-software.de/forum/index.php?topic=1847.0
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
AlphaControls
There is a project on Codeplex that can help you with transparency called AlphaControls. Also have a look on codeproject at the iPhone app clone
moneytoo said:
You can use ImagingFactory in OpenNETCF or other wrapper over the internet. PNGs with alpha work work for me.
Click to expand...
Click to collapse
Thank you all for answers ...
I tried OpenNetCF, without any result.
Do you have a piece of code in example ?
Try this:
http://www.codeplex.com/alphamobilecontrols
Or this:
http://johan.andersson.net/blog/2007/10/solution-for-transparent-images-on.html
Related
OK I am writing my first Mobile 6 App, based on compact framework 2, obviously finding some differences from Framwork vs compact when dealing with reading and writting simple values to xml;
Here is what I want to do: write two textbox values to xml as follows:
<settings>
<hostip>192.168.0.14</hostip>
<hostport>8011</hostport>
</settings>
So I got the above accomplished using the following code:
--------------------
string hstip = "";
string hstport = "";
hstip = this.HostIP.Text.ToString();
hstport = this.HostPort.Text.ToString();
XmlWriterSettings xml_settings = new XmlWriterSettings();
xml_settings.Indent = true;
xml_settings.OmitXmlDeclaration = false;
xml_settings.Encoding = Encoding.UTF8;
xml_settings.ConformanceLevel = ConformanceLevel.Auto;
using (XmlWriter xml = XmlTextWriter.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.WriteStartElement("settings");
//xml.WriteStartAttribute("hostip", "");
xml.WriteElementString("hostip", hstip);
//xml.WriteString(hstip);
//xml.WriteEndAttribute();
xml.WriteElementString("hostport", hstport);
//xml.WriteStartAttribute("hostport", "");
//xml.WriteString(hstport);
//xml.WriteEndAttribute();
xml.WriteEndElement();
//ds.WriteXml(xml);
xml.Close();
}
-----------end of write code------------
Now the part I am stumped on as I have tried all varietions to get the data back into the textboxes, I either get and exception or blank values in the textboxes.
Here is the code:
------------------
private void SrvSettings_Load(object sender, EventArgs e)
{
XmlReaderSettings xml_settings = new XmlReaderSettings();
xml_settings.IgnoreComments = true;
xml_settings.IgnoreProcessingInstructions = true;
xml_settings.IgnoreWhitespace = true;
xml_settings.CloseInput = true;
try
{
using (XmlReader xml = XmlTextReader.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.ReadStartElement("settings");
xml.Read();
xml.ReadElementString(,,)
//xml.ReadToFollowing("hostip");
this.HostIP.Text = xml.GetAttribute("hostip","");
//this.HostIP.Text = xml.GetAttribute("hostip");
//xml.ReadToFollowing("hostport");
this.HostPort.Text = xml.GetAttribute("hostport","");
// Close it out----------------
xml.ReadEndElement();
xml.Close();
//ds.ReadXml(xml);
// }
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(
ex.ToString(), "Error Loading IP settings");
}
}
------------end of read code
obviously I get an exception with this:
"System.xml.xmlexception:
"Text" is an invalid XmlNoteType. Line 2, posistion 11 at
System.xml.xmlReader.ReadEndElement()"
-----
I suspect I need to use ReadElementString, but I have tried and no workie...
Somebody have an example/class for both reading and writing per my requirements above, I would really appreciate the help..
Use XmlDocument
Try using the XmlDocument instead. It's alot easier to use for simple xml reading/writing.
Well Partially working now - I get the Hostport populated but for some reason hostip is blank even though it appears it falls through it in the case statement.. wierd..
DataSet ds = new DataSet();
XmlReaderSettings xml_settings = new XmlReaderSettings();
xml_settings.IgnoreComments = true;
xml_settings.IgnoreProcessingInstructions = true;
xml_settings.IgnoreWhitespace = true;
xml_settings.CloseInput = true;
try
{
using (XmlReader xml = XmlTextReader.Create(GetApplicationDirectory() + @"\settings.xml", xml_settings))
{
xml.MoveToContent();
xml.ReadStartElement("settings");
while (xml.Read())
{
//xml.Read();
switch (xml.Name)
{
case "hostip":
HostIP.Text = xml.ReadString(); <--I get Blank text
break;
case "hostport":
HostPort.Text = xml.ReadString(); <--POpulated OK
break;
default:
break;
}
// Close it out----------------
//xml.ReadEndElement();
}
xml.Close();
//ds.ReadXml(xml);
// }
}
}
Solved, Had to remove the line: xml.ReadStartElement("settings");
Thanks..
Just out of curiosity, what will your app do ?
I'm writing a WPF Windows App that monitors Server Services, IPs, Websites for up or down status; buiding a client server component to it, so the end goal will be to use the mobile app to connect to the host and download status on said servers being monitored and populate them in a listview whith thier up or done status.
Simple app but still in the works.
if you can make it customizable (to set up parametres, adreses) it wil be useful for many website administrators
a cool little app
Hi,
im playing around with the Camera Service. The preview mode works well, but if I take a picture and save it, it is a lot darker as in the preview. I tried it with the delivered camera app and there is no such problem.
I tried it with many diffrent values (iso, brightness, scenemode, whitebalance), but nothing changed, but the preview. It seems, that the preferences only have effect in the previewmode.
Device: altek A14 leo
OS: Android 2.1
Picture saved by the standard camera app:
abload.de/img/stdapp8uql.jpg
Preview mode:
abload.de/img/previewrne6.jpg
Picture saved by my app:
abload.de/img/myappiugc.jpg
parameters of the camera
Code:
atk-frame=0
brightness-max=12
brightness-min=0
brightness=6
camera-id=1
contrast-max=2
contrast-min=0
contrast=1
effect-values=none,mono,sepia,whiteboard
effect=none
flash-mode-values=off,auto,on,red-eye
flash-mode=off
focus-mode-values=auto,infinity
focus-mode=auto
gps-altitude=0
gps-latitude=0.0
gps-longitude=0.0
gps-timestamp=1199145600
iso-values=auto,80,100,200,400,800,1600,3200
iso=auto
jpeg-quality=100
jpeg-thumbnail-height=384
jpeg-thumbnail-quality=100
jpeg-thumbnail-width=512
max-zoom=9
metering-values=spot,center,matrix
metering=center
min-zoom=0
orientation=landscape
picture-format-values=jpeg
picture-format=jpeg
picture-size-values=2048x1536,1280x960
picture-size=2048x1536
preview-format-values=yuv420sp
preview-format=yuv420sp
preview-frame-rate-values=15
preview-frame-rate=15
preview-size-values=640x480
preview-size=640x480
rotation=0
saturation-max=0
saturation-min=2
saturation=1
scene-mode-values=auto,portrait,landscape,night,beach,snow,sunset,fireworks,sports,candlelight
scene-mode=auto
SD9-poweron-mode=0
sharpness-max=2
sharpness-min=0
sharpness=1
smooth-zoom-supported=true
whitebalance-values=auto,fluorescent,daylight,cloudy-daylight
whitebalance=auto
zoom-factors=100,130,160,190,220,250,280,310,340,360,400
zoom-supported=true
zoom=0
Code:
private OnClickListener cameraClickListener = new OnClickListener() {
public void onClick(View v) {
inPreview = false;
cam.takePicture(null, null, photoCallback);
}
};
PictureCallback photoCallback = new PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
new SavePhotoTask().execute(data);
startPreview();
}
};
class SavePhotoTask extends AsyncTask<byte[], String, String> {
protected String doInBackground(byte[]... imageData) {
File photo = new File(Environment.getExternalStorageDirectory(), "photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(imageData[0]);
fos.close();
Log.i("IMAGE SAVED ASYNC", photo.getPath());
} catch (java.io.IOException e) {
Log.e("Error", "Exception in photoCallback", e);
}
return (null);
}
}
Does anybody have an idea, what causes this behaviour?
thanks.
rgds
I am not sure what happening with you. But as far as your codes it should work well. try other camera apps. Like 360. But problem persist then go to service center. The problem is with hardware.
Hi,
sorry for the late response. It was no hardware issue. I just had to call autoFocus and takePicture in the AutoFocusCallback.
Code:
private OnClickListener cameraClickListener = new OnClickListener() {
public void onClick(View v) {
if (!isFocusing) {
isFocusing = true;
cam.autoFocus(autoFocusCallback);
}
}
};
AutoFocusCallback autoFocusCallback = new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
if (success) {
isFocusing = false;
camera.takePicture(null, null, photoCallback);
}
}
};
regards
Here are the adapter and asynctask class
Code:
class Myadapter extends ArrayAdapter<Layoutelements> {
Context context;
public Myadapter(Context context, int resourceId,List<Layoutelements> items) {
super(context, resourceId, items);
this .context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView( int position, View convertView, ViewGroup parent) {
ViewHolder holder = null ;
Layoutelements rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.rowlayout, null );
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.secondLine);
holder.txtTitle = (TextView) convertView.findViewById(R.id.firstline);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.txtDesc.setText(rowItem.getDesc().toString());
holder.txtTitle.setText(rowItem.getTitle());
String ext=getFileExtension(rowItem.getDesc());
if(ext.equals(".apk"))
{holder.imageView.setImageDrawable(rowItem.getImageId());
holder.imageView.setTag(rowItem.getDesc());//
////tag of imageView == path
////to image
new ImageDownloaderTask(holder.imageView).execute(rowItem.getDesc());
}
else if(ext.equals(".png") || ext.equals(".jpg") || ext.equals(".jpeg"))
{holder.imageView.setImageDrawable(rowItem.getImageId());
holder.imageView.setTag(rowItem.getDesc());//
////tag of imageView == path
////to image
new LoadImage(holder.imageView).execute(rowItem.getDesc());
}
else{
holder.imageView.setImageDrawable(rowItem.getImageId());}
return convertView;
}
}
Code:
class ImageDownloaderTask extends AsyncTask<String, Void, Drawable> {
private final WeakReference<ImageView> imageViewReference;
private String path;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
@Override
// Actual download method, run in the task thread
protected Drawable doInBackground(String... params) {
// params comes from the execute() call: params[0] is the url.
path =params[0];
try{PackageManager pm=getPackageManager();
PackageInfo pi=pm.getPackageArchiveInfo(path,0);
//// the secret arethese two lines....
pi.applicationInfo.sourceDir=path;
pi.applicationInfo.publicSourceDir=path;
////
return pi.applicationInfo.loadIcon(pm);
}catch(Exception e){return getResources().getDrawable(R.drawable.apk);}
}
@Override
// Once the image is downloaded, associates it to the imageView
protected void onPostExecute(Drawable bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageDrawable(bitmap);
} else {
imageView.setImageDrawable(imageView.getContext().getResources()
.getDrawable(R.drawable.apk));
}
}
}
}
}
I am making a file manager.
Now the problem is like this.
If i scroll down icons load correctly. But when i scroll up, the icons load again.they are not cached once they are loaded.i want that icons are cached till directory is changed.
Sent from my GT-S5570 using XDA Premium 4 mobile app
arpitkh96 said:
I am making a file manager.
Now the problem is like this.
If i scroll down icons load correctly. But when i scroll up, the icons load again.they are not cached once they are loaded.i want that icons are cached till directory is changed.
Click to expand...
Click to collapse
Try using an LruCache or your images. Also, you might want to take a look at this guide explaining it further.
SimplicityApks said:
Try using an LruCache or your images. Also, you might want to take a look at this guide explaining it further.
Click to expand...
Click to collapse
Thanks i will check them
Sent from my GT-S5570 using XDA Premium 4 mobile app
It worked but is buggy.the images many times get blurred after scrolling up as shown in screenshots.See the thumbnails in both images
Sent from my GT-S5570 using XDA Premium 4 mobile app
After scroll
Is this due to low cache memory.should i try on another device.should i show you the new modified code.
Sent from my GT-S5570 using XDA Premium 4 mobile app
I have a large data to load from JSON.
I have implemented a custom list view by following a tutorial, now since the data is huge I want it load as the user scrolls.
This is my LoadRestaurant class code which is inside the main activity.
Code:
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(SearchAll.this, RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
intent.putExtra("login_id", loginId);
startActivity(intent);
}
});
}
});
}
}
}
I want to load around 20 restaurants and then it auto loads another 20 as soon as user reaches the end of first 20.
There are lots of tutorials online but its confusing to implement.
Please help me out!
The custom ListView, support for automatic loading you can try https://github.com/chrisbanes/Android-PullToRefresh
As what was stated on the header I want to implement either a "paint" function for user to edit paint/censor unwanted parts of a photo displayed on a imageview before uploading it to a server in the edited format and a redo function if user makes a mistake while editing?
How do I come about doing it, I've read relevant topics on Canvas, or FingerPaint but still puzzled on how to implement it based on my project here? Tried referencing to the links here and here but without success in implementing the codes into my project code due to my lack of programming skills.
Thanks for any help rendered!
Tried integrating the codes below into my code above (image preview after taking a photo with the camera) for user to start editing via painting but still not working? Thanks for any help rendered!
Code:
public class Drawing extends View {
private Paint mPaint, mBitmapPaint;
Intent intent = getIntent();
Bitmap mBitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
private Canvas mCanvas;
private Path mPath;
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private int color, size, state;
private ArrayList<Path> paths = new ArrayList<Path>();
private ArrayList<Path> undonePaths = new ArrayList<Path>();
private ArrayList<Integer> colors = new ArrayList<Integer>();
private ArrayList<Integer> sizes = new ArrayList<Integer>();
public Drawing(Context c) {
super(c);
}
public Drawing(Context c,int width, int height, int size, int color, int state) {
super(c);
mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
mCanvas = new Canvas(mBitmap);
mPath = new Path();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
// mBitmapPaint = new Paint(Paint.DITHER_FLAG);
// mBitmapPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC));
setColor(color);
setSize(size);
setState(state);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
@Override
protected void onDraw(Canvas canvas) {
// canvas.drawColor(Color.TRANSPARENT);
// canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
//
// if (state == 0)
// mBitmap.eraseColor(Color.TRANSPARENT);
for (int i = 0; i < paths.size(); i++) {
mPaint.setColor(colors.get(i));
mPaint.setStrokeWidth(sizes.get(i));
canvas.drawPath(paths.get(i), mPaint);
}
mPaint.setColor(color);
mPaint.setStrokeWidth(size);
canvas.drawPath(mPath, mPaint);
}
public void setColor(int color) {
this.color = color;
}
public void setSize(int size) {
this.size = size;
}
public void setState(int state) {
this.state = state;
// if (state == 0)
// mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
// else
// mPaint.setXfermode(null);
}
public void onClickUndo() {
if (paths.size() > 0) {
undonePaths.add(paths.remove(paths.size() - 1));
sizes.remove(sizes.size() - 1);
colors.remove(colors.size() - 1);
invalidate();
}
}
private void touch_start(float x, float y) {
undonePaths.clear();
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
mCanvas.drawPath(mPath, mPaint);
colors.add(color);
sizes.add(size);
paths.add(mPath);
mPath = new Path();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touch_start(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
invalidate();
break;
}
return true;
}
}