xamarin form button background color in custom renderer - windows-phone-8.1

I am trying to set the background color in xamarin form. To achieve that I thought I might use CustomRenderer. I want to set the background color from Hex value. Below is my code where I am finding hard to set the background color. I want to set it in windows 8.1 and UWP. I will really appreciate if some one can tell me on how do it in android as well.
[assembly: ExportRendererAttribute(typeof(PrimaryButton), typeof(PrimaryButtonRenderer))]
namespace ShareSpecial.Windows
{
public class PrimaryButtonRenderer : ButtonRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.BackgroundColor = //some color from hex string
}
}
}
}

the Color class in Xamarin Forms has a method FromHex, and you can easily implement extension methods for color conversion in each platform. in Android there is already a default implementation named ToAndroid().
For WP8 and UWP:
Define this extension:
static class ConvertExtensions
{
public static Windows.UI.Color ToWindowsColor(this Color color)
{
return Windows.UI.Color.FromArgb((byte)(color.A * 255), (byte)(color.R * 255), (byte)(color.G * 255), (byte)(color.B * 255));
}
}
And the code of your renderer would be:
Control.BackgroundColor = new SolidColorBrush(Color.FromHex("ffffffff").ToWindowsColor());
For Android:
If you change the backgroundColor using SetBackgroundColor() method, you will lose the effect of click, to keep it, use the below code:
Color backgroundColor = Color.FromHex("ffffffff");
int num = backgroundColor.ToAndroid().ToArgb();
int num2 = backgroundColor.MultiplyAlpha(0.5).ToAndroid().ToArgb();
base.Control.SupportBackgroundTintList = new ColorStateList(ColorExtensions.States, new int[] {
num,
num2
});
You will have to extend your renderer from: Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer

You should use SolidColorBrush for setting a color of Windows Platform element.
Control.BackgroundColor = ToWindowsBrush(Color.Red);
Here is a method that converts Xamarin.Froms.Color to SolidColorBrush
public static SolidColorBrush ToWindowsBrush(Xamarin.Forms.Color color)
{
if (color.A < 0)
return new SolidColorBrush(Windows.UI.Colors.Transparent);
var winColor = Windows.UI.Color.FromArgb((byte)(color.A * 255),
(byte)(color.R * 255),
(byte)(color.G * 255),
(byte)(color.B * 255));
return new SolidColorBrush(winColor);
}

Got it working with help from #Hichaam and posting the working android solution
using Xamarin.Forms.Platform.Android;
using Xamarin.Forms;
using ShareSpecial.Utils.Controls;
using ShareSpecial.Droid.Custom.Control.Buttons;
using Android.Content.Res;
[assembly: ExportRendererAttribute(typeof(SuccessButton), typeof(SuccessButtonRenderer))]
namespace ShareSpecial.Droid.Custom.Control.Buttons
{
public class SuccessButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
{
public SuccessButtonRenderer() { }
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> changeEvent)
{
base.OnElementChanged(changeEvent);
var backgroundColor = Color.FromHex("43ac6a");
int num = backgroundColor.ToAndroid().ToArgb();
int num2 = backgroundColor.MultiplyAlpha(0.5).ToAndroid().ToArgb();
Control.SupportBackgroundTintList = new ColorStateList(ColorExtensions.States, new int[] { num, num2 });
Control.SetTextColor(Color.FromHex("#ffffff").ToAndroid());
}
}
}

Related

Unable to add BarCode in 'cshtml' using TagHelper in ASP.NET core 2.0 class project

I'm using here TagHelper concept in ASP.Net core 2.0 class library.
using Microsoft.AspNetCore.Razor.TagHelpers;
using ZXing.QrCode;
using System.Drawing;
using System.IO;
using System;
namespace DRC.Taxpayer.TagHelpers
{
[HtmlTargetElement("barcode")]
public class BarCodeTagHelper : TagHelper
{
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var content = context.AllAttributes["content"].Value.ToString();
var width = int.Parse(context.AllAttributes["width"].Value.ToString());
var height = int.Parse(context.AllAttributes["height"].Value.ToString());
var barcodeWriterPixelData = new ZXing.BarcodeWriterPixelData
{
Format = ZXing.BarcodeFormat.CODE_128,
Options = new QrCodeEncodingOptions
{
Height = height,
Width = width,
Margin = 0
}
};
var pixelData = barcodeWriterPixelData.Write(content);
using (var bitmap = new Bitmap(pixelData.Width, pixelData.Height, System.Drawing.Imaging.PixelFormat.Format32bppRgb))
{
using (var memoryStream = new MemoryStream())
{
var bitmapData = bitmap.LockBits(new Rectangle(0, 0, pixelData.Width, pixelData.Height), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
try
{
System.Runtime.InteropServices.Marshal.Copy(pixelData.Pixels, 0, bitmapData.Scan0, pixelData.Pixels.Length);
}
finally
{
bitmap.UnlockBits(bitmapData);
}
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Png);
output.TagName = "img";
output.Attributes.Clear();
output.Attributes.Add("width", width);
output.Attributes.Add("height", height);
output.Attributes.Add("src", string.Format("data:image/png,base64,{0}", Convert.ToBase64String(memoryStream.ToArray())));
}
}
}
}
}
In CSHTML I've added below tag helpers:
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers;
#addTagHelper *, BarCodeTagHelper;
To set barCode in cshtml (using razor engin i.e. RazorEngine.Core.NetCore, I've added below a line of code:
But when I execute the application, it is not considering the tag helper and keeping it as a blank.
Am I doing something wrong in this?
Is it the correct approach I'm using here to generate barcode? Is there any other way to do it in ASP.Net core 2.0?
I have tried implementing the solution provided in this answer but it is not working for me.

Libgdx crop image to circle

I'm looking for a way to crop a photo taken from the users gallery to a circle, to be displayed as a profile picture basically.
I've been recommended to use Masking .
But I can't work out how to actually do it. There are virtually no examples of it, except with android code. But since I'm going to port my game to IOS as well I need a Libgdx solution.
So has anyone done this before and have an working example perhaps?
Here's how I'll fetch the image:
ublic void invokeGallery() {
if (utils != null) {
loading = true;
utils.pickImage(new utilsInterface.Callback() {
#Override
public ImageHandler onImagePicked(final InputStream stream) {
loading = true;
final byte[] data;
try {
data = StreamUtils.copyStreamToByteArray(stream);
Gdx.app.postRunnable(new Runnable() {
#Override
public void run() {
loading = false;
}
});
} catch (IOException e) {
e.printStackTrace();
}
loading = false;
return null;
}
});
}
}
I use this, it works, but there is no interpolation, which means the edges are pixelated. You can chose to either implement interpolation or use a border!
public static Pixmap roundPixmap(Pixmap pixmap)
{
int width = pixmap.getWidth();
int height = pixmap.getHeight();
Pixmap round = new Pixmap(pixmap.getWidth(),pixmap.getHeight(),Pixmap.Format.RGBA8888);
if(width != height)
{
Gdx.app.log("error", "Cannot create round image if width != height");
round.dispose();
return pixmap;
}
double radius = width/2.0;
for(int y=0;y<height;y++)
{
for(int x=0;x<width;x++)
{
//check if pixel is outside circle. Set pixel to transparant;
double dist_x = (radius - x);
double dist_y = radius - y;
double dist = Math.sqrt((dist_x*dist_x) + (dist_y*dist_y));
if(dist < radius)
{
round.drawPixel(x, y,pixmap.getPixel(x, y));
}
else
round.drawPixel(x, y, 0);
}
}
Gdx.app.log("info", "pixmal rounded!");
return round;
}
Do keep in mind this will all be unmanaged! To make life easier I usually save the image and load it as a managed texture.

Navisworks COM API for Exporting geometry and calculating faces and vertices

I am trying to export the vertices, faces and colors of a selected object in the Navis. After a bit of research I found that we can do it using the COM API provided by the Navisworks. I used getprimitives to find the triangles. which looks is something as below.
'using Autodesk.Navisworks.Api;
using Autodesk.Navisworks.Api.Plugins;
using ComBridge = Autodesk.Navisworks.Api.ComApi.ComApiBridge;
using COMApi = Autodesk.Navisworks.Api.Interop.ComApi;
#region InwSimplePrimitivesCB Class
class CallbackGeomListener : COMApi.InwSimplePrimitivesCB
{
public void Line(COMApi.InwSimpleVertex v1,
COMApi.InwSimpleVertex v2)
{
// do your work
}
public void Point(COMApi.InwSimpleVertex v1)
{
// do your work
}
public void SnapPoint(COMApi.InwSimpleVertex v1)
{
// do your work
}
public void Triangle(COMApi.InwSimpleVertex v1,
COMApi.InwSimpleVertex v2,
COMApi.InwSimpleVertex v3)
{
// do your work
}
}
#endregion
#region NW Plugin
[PluginAttribute("Test","ADSK",DisplayName= "Test")]
[AddInPluginAttribute(AddInLocation.AddIn)]
public class Class1:AddInPlugin
{
public override int Execute(params string[] parameters)
{
// get the current selection
ModelItemCollection oModelColl =
Autodesk.Navisworks.Api.Application.
ActiveDocument.CurrentSelection.SelectedItems;
//convert to COM selection
COMApi.InwOpState oState = ComBridge.State;
COMApi.InwOpSelection oSel =
ComBridge.ToInwOpSelection(oModelColl);
// create the callback object
CallbackGeomListener callbkListener =
new CallbackGeomListener();
foreach (COMApi.InwOaPath3 path in oSel.Paths())
{
foreach (COMApi.InwOaFragment3 frag in path.Fragments())
{
// generate the primitives
frag.GenerateSimplePrimitives(
COMApi.nwEVertexProperty.eNORMAL,
callbkListener);
}
}
return 0;
}
}
#endregion
'
The problem here is I am not able to find faces, I do get vertices by using triangle method.
Please let me know if anyone knows how to find faces and color of the object.

Box2d body generation dynamically in cocos2dx using c++ in Xcode

I am a new developer in cocos2dx.I am developing a game in which i am using the box2d bodies that are loading through physics editor.There are more than 20 bodies using in a level of the game,that i am making separate body for separate sprite attached with them and the similar bodies are used in the other levels and there are 50 levels in the game and for each level,i have made separate class and again making the b2body loading function,all the code is working properly but I just want to make a generic function for loading the bodies in a class so that i can use the same b2body loading function in all the levels.Also i have to destroy the particular body and the sprite on touching the sprite
//Sprites:
rect_sprite1=CCSprite::create("rect1.png");
rect_sprite1->setScaleX(rX);
rect_sprite1->setScaleY(rY);
this->addChild(rect_sprite1,1);
rect_sprite2=CCSprite::create("rect2.png");
rect_sprite2->setScaleX(rX);
rect_sprite2->setScaleY(rY);
this->addChild(rect_sprite2,1);
rect_sprite3=CCSprite::create("circle.png");
rect_sprite3->setScale(rZ);
this->addChild(rect_sprite3,1);
GB2ShapeCache::sharedGB2ShapeCache()->addShapesWithFile("obs.plist");
//body loading function
void Level1::addNewSpriteWithCoords()
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
b2BodyDef bodyDef1;
bodyDef1.type=b2_dynamicBody;
bodyDef1.position.Set((winSize.width*0.38)/PTM_RATIO,(winSize.height*0.4) /PTM_RATIO);
bodyDef1.userData = rect_sprite1;
body1 = (MyPhysicsBody*)world->CreateBody(&bodyDef1);
body1->setTypeFlag(7);
// add the fixture definitions to the body
GB2ShapeCache *sc1 = GB2ShapeCache::sharedGB2ShapeCache();
sc1->addFixturesToBody(body1,"rect1", rect_sprite1);
rect_sprite1->setAnchorPoint(sc1->anchorPointForShape("rect1"));
b2BodyDef bodyDef2;
bodyDef2.type=b2_dynamicBody;
bodyDef2.position.Set((winSize.width*0.62)/PTM_RATIO,
(winSize.height*0.4)/PTM_RATIO);
bodyDef2.userData = rect_sprite2;
body2 = (MyPhysicsBody*)world->CreateBody(&bodyDef2);
body2->setTypeFlag(7);
// add the fixture definitions to the body
GB2ShapeCache *sc2 = GB2ShapeCache::sharedGB2ShapeCache();
sc2->addFixturesToBody(body2,"rect2", rect_sprite2);
rect_sprite2->setAnchorPoint(sc2->anchorPointForShape("rect2"));
b2BodyDef bodyDef3;
bodyDef3.type=b2_dynamicBody;
bodyDef3.position.Set((winSize.width*0.5)/PTM_RATIO, (winSize.height*0.23)/PTM_RATIO);
bodyDef3.userData = rect_sprite3;
body3 = (MyPhysicsBody*)world->CreateBody(&bodyDef3);
body3->setTypeFlag(7);
// add the fixture definitions to the body
GB2ShapeCache *sc3 = GB2ShapeCache::sharedGB2ShapeCache();
sc3->addFixturesToBody(body3,"circle", rect_sprite3);
rect_sprite3->setAnchorPoint(sc3->anchorPointForShape("circle"));
}
void Level1::ccTouchesBegan(cocos2d::CCSet* touches, cocos2d::CCEvent* event)
{
if(box->containsPoint(touchPoint))
{
this->removeChild(((CCSprite*)rect),true);
if(((CCSprite*)rect)==rect_sprite1)
{
rect_sprite1=NULL;
world->DestroyBody(body1);
Utils::setCount(Utils::getCount()-1);
}
if(((CCSprite*)rect)==rect_sprite2)
{
rect_sprite2=NULL;
world->DestroyBody(body2);
Utils::setCount(Utils::getCount()-1);
}
if(((CCSprite*)rect)==rect_sprite3)
{
rect_sprite3=NULL;
world->DestroyBody(body3);
Utils::setCount(Utils::getCount()-1);
}
}
Similarly i am doing for other levels.
If anyone know about it,please suggest.Thanks
This seems more like a "What design pattern should I use?" than a specific problem with loading the code.
In general, when I want to create "Entities" that require a physical body, I use a base class that contains the Box2D body as one of its members. The base class is a container for the body (which is assigned to it) and is responsible for destroying the body (removing it from the Box2D world) when the Entity is destroyed.
Derived classes can load the body from the Box2D shape cache. This is best shown through an example. There is a game I am working on where I have a swarm of different shaped asteroids circling a sun. Here is a screen shot:
The base class, Entity, contains the body and destroys it when the Entity is destroyed:
class Entity : public HasFlags
{
public:
enum
{
DEFAULT_ENTITY_ID = -1,
};
private:
uint32 _ID;
// Every entity has one "main" body which it
// controls in some way. Or not.
b2Body* _body;
// Every entity has a scale size from 1 to 100.
// This maps on to the meters size of 0.1 to 10
// in the physics engine.
uint32 _scale;
protected:
void SetScale(uint32 value)
{
assert(value >= 1);
assert(value <= 100);
_scale = value;
}
public:
void SetBody(b2Body* body)
{
assert(_body == NULL);
if(_body != NULL)
{
CCLOG("BODY SHOULD BE NULL BEFORE ASSIGNING");
_body->GetWorld()->DestroyBody(_body);
_body = NULL;
}
_body = body;
if(body != NULL)
{
_body->SetUserData(this);
for (b2Fixture* f = _body->GetFixtureList(); f; f = f->GetNext())
{
f->SetUserData(this);
}
}
}
inline void SetID(uint32 ID)
{
_ID = ID;
}
inline uint32 GetID() const
{
return _ID;
}
virtual string ToString(bool updateDescription = false)
{
string descr = "ID: ";
descr += _ID;
descr += "Flags: ";
if(IsFlagSet(HF_IS_GRAPH_SENSOR))
descr += "IS_FLAG_SENSOR ";
return descr;
}
Entity() :
_ID(DEFAULT_ENTITY_ID),
_body(NULL),
_scale(1)
{
}
Entity(uint32 flags, uint32 scale) :
HasFlags(flags),
_ID(DEFAULT_ENTITY_ID),
_body(NULL),
_scale(scale)
{
}
virtual void Update()
{
}
virtual void UpdateDisplay()
{
}
virtual ~Entity()
{
if(_body != NULL)
{
_body->GetWorld()->DestroyBody(_body);
}
}
inline static float32 ScaleToMeters(uint32 scale)
{
return 0.1*scale;
}
inline Body* GetBody()
{
return _body;
}
inline const Body* GetBody() const
{
return _body;
}
inline uint32 GetScale()
{
return _scale;
}
inline float32 GetSizeMeters()
{
return ScaleToMeters(_scale);
}
};
The Asteroid class itself is responsible for loading one of several different "Asteroid" shapes from the shape cache. However, ALL the asteroids have common logic for making them move about the center of the screen. They have a rope joint attached and the Update(...) function adds some "spin" to them so they rotate around the center:
class Asteroid : public Entity
{
private:
b2Fixture* _hull;
Vec2 _anchor;
CCSprite* _sprite;
float32 _targetRadius;
public:
// Some getters to help us out.
b2Fixture& GetHullFixture() const { return *_hull; }
float32 GetTargetRadius() { return _targetRadius; }
CCSprite* GetSprite() { return _sprite; }
void UpdateDisplay()
{
// Update the sprite position and orientation.
CCPoint pixel = Viewport::Instance().Convert(GetBody()->GetPosition());
_sprite->setPosition(pixel);
_sprite->setRotation(-CC_RADIANS_TO_DEGREES(GetBody()->GetAngle()));
}
virtual void Update()
{
Body* body = GetBody();
Vec2 vRadius = body->GetPosition();
Vec2 vTangent = vRadius.Skew();
vTangent.Normalize();
vRadius.Normalize();
// If it is not moving...give it some spin.
if(fabs(vTangent.Dot(body->GetLinearVelocity())) < 1)
{
body->SetLinearDamping(0.001);
body->ApplyForceToCenter(body->GetMass()*1.5*vTangent);
body->ApplyForce(vRadius,body->GetMass()*0.05*vRadius);
}
else
{
body->SetLinearDamping(0.05);
}
}
~Asteroid()
{
}
Asteroid() :
Entity(HF_CAN_MOVE | HF_UPDATE_PRIO_5,50)
{
}
bool Create(b2World& world, const string& shapeName,const Vec2& position, float32 targetRadius)
{
_targetRadius = targetRadius;
_anchor = position;
string str = shapeName;
str += ".png";
_sprite = CCSprite::createWithSpriteFrameName(str.c_str());
_sprite->setTag((int)this);
_sprite->setAnchorPoint(ccp(0.5,0.5));
// _sprite->setVisible(false);
b2BodyDef bodyDef;
bodyDef.position = position;
bodyDef.type = b2_dynamicBody;
Body* body = world.CreateBody(&bodyDef);
assert(body != NULL);
// Add the polygons to the body.
Box2DShapeCache::instance().addFixturesToBody(body, shapeName, GetSizeMeters());
SetBody(body);
return true;
}
};
The Create(...) function for the Asteroid is called from the loading code in the scene, which could easily be a .csv file with the shape names in it. It actually reuses the names several times (there are only about 10 asteroid shapes).
You will notice that the Asteroid also has a CCSprite associated with it. Not all Entities have a sprite, but some do. I could have created an Entity-Derived class (EntityWithSprite) for this case so that the sprite could be managed as well, but I try to avoid too many nested classes. I could have put it into the base class, and may still. Regardless, the Asteroids contain their own sprites and load them from the SpriteCache. They are updated in a different part of the code (not relevant here, but I will be happy to answer questions about it if you are curious).
NOTE: This is part of a larger code base and there are features like zooming, cameras, graph/path finding, and lots of other goodies in the code base. Feel free to use what you find useful.
You can find all the (iOS) code for this on github and there are videos and tutorials posted on my site here.

Intermediate image

I have a problem with intermediate image. The image is showing only once. After i move the image "line" is not showing anymore.
public void paintLine(Graphics g) {
if (line == null) {
line = new BufferedImage(1, height, BufferedImage.TYPE_INT_ARGB);
Graphics gImg = line.getGraphics();
float[] data = datas[index];
for (float f : data) {
float[] rgb = ColorMap.getPixelColor(f);
gImg.setColor(new Color(rgb[0], rgb[1], rgb[2]));
gImg.drawRect(0, (int)yPos--, 1, 1);
}
gImg.dispose();
}
xIncr++;
g.drawImage(line, (int)xPos - xIncr, (int)yPos, null);
graph.repaint();
}
This method is called in paintComponent ofJPanel.
If i recreate the image "line" each time, it is displaying properly with really poor performance.
Emm... I am not pretty sure owing to less information in your question but, as a rule, image may disappear because of doubleBuffered(false) option. So you need to set the double buffered option to true manually for your canvas. Code something like this
public class MyLabel extends JLabel{
public MyLabel()
{
this.setDoubleBuffered(true);
}
public void paintComponent(Graphics g)
{
this.paintLine(g);
}
public void paintLine(Graphics g) {
if (line == null) {
line = new BufferedImage(1, height, BufferedImage.TYPE_INT_ARGB);
Graphics gImg = line.getGraphics();
float[] data = datas[index];
for (float f : data) {
float[] rgb = ColorMap.getPixelColor(f);
gImg.setColor(new Color(rgb[0], rgb[1], rgb[2]));
gImg.drawRect(0, (int)yPos--, 1, 1);
}
//gImg.dispose();
}
xIncr++;
g.drawImage(line, (int)xPos - xIncr, (int)yPos, null);
graph.repaint();
}
}
Now I guess the conception is more clear
Good luck