How to use custom views, e.g. setting drawable - android

I think I'm a bit confused about how to use custom views. I'm following along with slides from a talk given by Eric Burke from Square (from this year's anddevcon, slides here: http://www.andevcon.com/AndevCon_II/downloadpresentation.aspx?aid=Taming_Android__User_Experience_Lessons_from_Square_pdf.zip&sid=2).
His code, or at least the part he showed in the slides, went something like this:
public class EditablePhoto extends View {
private Bitmap framedPhoto;
private Bitmap image;
private Drawable placeholder;
public EditablePhoto(Context context) {
super(context);
}
#Override protected void onMeasure(int widthMeasureSpec,
int heightMeasureSpec) {
int measuredWidth = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
int measuredHeight = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
//ensure view always square
int min = Math.min(measuredHeight, measuredWidth);
setMeasuredDimension(min, min);
}
#Override
protected void onDraw(Canvas canvas) {
if(placeholder == null && image==null) return;
if(framedPhoto == null) {
createFramedPhoto(Math.min(getWidth(), getHeight()));
}
canvas.drawBitmap(framedPhoto, 0, 0, null);
}
private void createFramedPhoto(int size) {
Drawable imageDrawable = (image!=null)
? new BitmapDrawable(image) : placeholder;
Bitmap output = Bitmap.createBitmap(size, size,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
RectF outerRect = new RectF(0, 0, size, size);
float outerRadius = size / 18f;
//Red rectangle
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
canvas.drawRoundRect(outerRect, outerRadius, outerRadius, paint);
paint.setXfermode(new PorterDuffXfermode(
PorterDuff.Mode.SRC_IN));
imageDrawable.setBounds(0, 0, size, size);
canvas.saveLayer(outerRect, paint, Canvas.ALL_SAVE_FLAG);
imageDrawable.draw(canvas);
canvas.restore();
}
}
What I don't get is how to actually use this View now.... Where and when do you set the bitmaps, which are private fields in this class...?
Generally confused and would love some enlightenment.

More than one year passed, but I hope this will help anyone who looking for the right answer. In my case, I putted this line of code
framedPhoto = output;
as the last one in createFramedPhoto() method. It works.
In the example, the author created a rounded rectangle as background then he draw the bitmap on it with XOR mode, so all pixel outside the rounded rectangle will be trim off.

OnDraw() is the method where you will Draw your view on canvas. here too you can analyze onDraw() will fisrt call CreateFramePhoto then draw this Bitmap on canvas .
You can add this customView in layout Either from xml or in Java Class
1) Through Xml :
<EditablePhoto android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
..........................
/>
dont forgate to add constructor EditablePhoto(Context context, AttributeSet attributeSet) for this case
2) through Java class :
EditablePhoto editablePhoto = new EditablePhoto(this);
addView(editablePhoto) // or do anthing you want with this

Related

Android: Change size of canvas / drawable in custom drawable

I'm trying to implement a custom drawable which should have the shape of a speechbubble. Therefore I use two paths, one draws the rect and the other should draw the triangle for the bubble.
My class looks like the following:
public class SpeechBubbleView extends Drawable {
private Paint mBubblePaint;
private Paint mBubblePaint2;
private Path mRectPath;
private Path mBubblePath;
public SpeechBubbleView() { }
public void initPaint() {
mBubblePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBubblePaint.setStyle(Paint.Style.FILL);
mBubblePaint.setColor(Color.GREEN);
mBubblePaint2 = new Paint(Paint.ANTI_ALIAS_FLAG);
mBubblePaint2.setStyle(Paint.Style.FILL);
mBubblePaint2.setColor(Color.RED);
int width = getBounds().width();
int height = getBounds().height();
mRectPath = new Path();
mRectPath.addRoundRect(new RectF(0, 0, width, height), 8, 8, Path.Direction.CW);
mRectPath.close();
mBubblePath = new Path();
mBubblePath.moveTo(50, height);
mBubblePath.lineTo(100, height + 50);
mBubblePath.lineTo(150, height);
mBubblePath.close();
}
#Override
public void draw(Canvas canvas) {
if(mRectPath == null && mPathValues == null) {
initPaint();
}
canvas.drawPath(mRectPath, mBubblePaint);
canvas.drawPath(mBubblePath, mBubblePaint2);
}
#Override
public void onBoundsChange(Rect bounds) {
Rect customBound = new Rect(0, 0, bounds.width(), bounds.height() + 50);
super.onBoundsChange(customBound);
}
The problem now is, that I take the width and height from the drawable to draw the rect of the speechbubble. The full space of the canvas is taken and there is no more room for the triangle to display below the rect.
My question now is: Is it possible to change the size of canvas or the drawable, so that I am able to display the small triangle below the rect?
I already tried the method onBoundsChange, but it takes no effect. In the draw-method the size is still the same.
If possible, it would be nice to change the size directly in the custom drawable class, shown above, because I do not have the size of the view, when I call it. Also I cannot make the size of the rect smaller, because in the drawable there is content and if the rect is smaller, some of the content will be outside of the drawable. I use a drawable, so that I can simple call setBackgroundDrawable of my layout or TextView and it matches always the content size.
If anyone of you got an idea on how to do the size change, this would be very great. Thank you :D

Creating a shadow around a canvas drawn shape?

What steps are required to create a shape e.g. rectangle with a shadow from scratch using a Canvas?
Adding a shadow layer to the paint used to draw the rectangle yielded no success.
No need for a Bitmap, just needed to set the layer type to LAYER_TYPE_SOFTWARE the original approach worked.
public class TestShapeShadow extends View
{
Paint paint;
public TestShapeShadow(Context context)
{
super(context);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setShadowLayer(12, 0, 0, Color.YELLOW);
// Important for certain APIs
setLayerType(LAYER_TYPE_SOFTWARE, paint);
}
#Override
protected void onDraw(Canvas canvas)
{
canvas.drawRect(20, 20, 100, 100, paint);
}
}
I followed the ideas in #pskink's answer and found a solution.
I put the code snippet here for anyone in need.
public class MyViewWithShadow extends View {
Paint paint;
int mainColor;
int shadowColor;
// shadow properties
int offsetX = -25;
int offsetY = 30;
int blurRadius = 5;
public MyViewWithShadow(Context context)
{
super(context);
mainColor = Color.RED;
shadowColor = Color.BLACK; // this color can also have alpha
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
}
#Override
protected void onDraw(Canvas canvas)
{
// Create paint for shadow
paint.setColor(shadowColor);
paint.setMaskFilter(new BlurMaskFilter(
blurRadius /* shadowRadius */,
BlurMaskFilter.Blur.NORMAL));
// Draw shadow before drawing object
canvas.drawRect(20 + offsetX, 20 + offsetY, 100 + offsetX, 100 + offsetY, paint);
// Create paint for main object
paint.setColor(mainColor);
paint.setMaskFilter(null);
// Draw main object
canvas.drawRect(20, 20, 100, 100, paint);
}
}
[Link is now broken:]
If you wonder what shadow properties are, you can refer to this tester:
https://okawa-h.github.io/box-shadow_tester/~
create. a Path, add some elements to it
set BlurMaskFilter to a Paint
draw a path with dx, dy shadow offset
unset mask filter
draw a path again with no. offset

Antialiased rounded corners on Android ImageView [duplicate]

This question already has answers here:
How to make an ImageView with rounded corners?
(58 answers)
Closed 9 years ago.
I am new to android dev, and I have been trying for a few hours now to add nice and smooth rounded corners to an ImageView, without success.
First thing I tried is simply to round corners of my images directly, but this implies changing the bitmap, and since I need to keep the raw ones, and those are pretty big, this is not really memory friendly. This would also cause other difficulties since my ImageView is fluid.
Second thing I tried to use is the clipPath method after subclassing my view. This works, but corners are aliased. I then tried adding a PaintFlagsDrawFilter to implement the aliasing, but this didn't worked. I'm using monodroid, and I was wondering this was supposed to work in Java.
Here is my code (C#):
public class MyImageView : ImageView
{
private float[] roundedCorner;
/**
* Contains the rounded corners for the view.
* You can define one, four or height values.
* This behaves as the css border-radius property
*
* #see http://developer.android.com/reference/android/graphics/Path.html#addRoundRect(android.graphics.RectF, float[], android.graphics.Path.Direction)
*/
public float[] RoundedCorners{
get{
return roundedCorner;
}
set{
float[] finalValue = new float[8];
int i=0;
if(value.Length == 1){
for(i=0; i<8;i++){
finalValue[i] = value[0];
}
}else if(value.Length == 4){
for(i=0; i<4;i++){
finalValue[2*i] = value[i];
finalValue[2*i+1] = value[i];
}
}
roundedCorner = finalValue;
}
}
public SquareImageView (Context context) :
base (context)
{
Initialize ();
}
public SquareImageView (Context context, IAttributeSet attrs) :
base (context, attrs)
{
Initialize ();
}
private void Initialize ()
{
RoundedCorners = new float[]{0,0,0,0};
}
public override void Draw (Android.Graphics.Canvas canvas)
{
Path path = new Path();
path.AddRoundRect(new RectF(0,0, Width,Height),RoundedCorners, Path.Direction.Cw);
canvas.ClipPath(path);
base.Draw (canvas);
}
/**
* try to add antialiasing.
*/
protected override void DispatchDraw (Canvas canvas)
{
canvas.DrawFilter = new PaintFlagsDrawFilter((PaintFlags)1, PaintFlags.AntiAlias);
base.DispatchDraw (canvas);
}
}
Thanks for your help!
I've created a RoundedImageView based off Romain Guy's example code that wraps this logic into an ImageView that you should be able to just use. It supports borders and antialiasing out of the box.
It's more efficient than other rounded corner examples because it doesn't create another copy of the bitmap, nor does it use clipPath which draws twice to the canvas.
use below code
public Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels)
{
Bitmap output = null;
if(bitmap != null)
{
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
}
return output;
}
and call this method like
imageView.setImageBitmap(getRoundedCornerBitmap(bitmap, 10));

Custom view's onDraw receives canvas with different sizes

I have a class derived from ImageView:
public class TouchView extends ImageView
{
#Override
protected void onDraw(Canvas canvas)
...
The touchview is created only once in the activity's onCreate and populated with a drawable from a SVG file.
ImageView imageView = new TouchView(this);
imageView.setScaleType(ImageView.ScaleType.MATRIX);
FrameLayout f = (FrameLayout)findViewById(R.id.frame2);
FrameLayout.LayoutParams l = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.FILL_PARENT, FrameLayout.LayoutParams.FILL_PARENT);
f.addView(imageView, l);
...
is = openFileInput(svgname);
svg = SVGParser.getSVGFromInputStream(is);
is.close();
Drawable d = svg.createPictureDrawable();
imageView.setImageDrawable(d);
All the environment remains the same all the time. Yet in the onDraw method I'm getting canvas with different sizes between the events. That is the code:
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
Log.v("DRAW", " w= " + canvas.getWidth() + " h=" + canvas.getHeight());
...
}
produces logs with lines, where width and height of the canvas change back and forth from normal 1024*728 (this is the correct view dimension on the tablet) to 200*160 (strange thing introducing bugs in my drawings). I'm embarrassed.
Should the canvas be always of the same size for the same view/drawable? The documentation says that getWidth and getHeight methods return dimensions of the current drawing layer, but it's not clear what is the layer, how many of them is created for the canvas "behind the scene" and how to control this process.
I'd appreciate any explanation on how to get consistent drawing behaviuor, specifically by getting actual size of the view being painted in onDraw.
Currently I'm using a workround with a call to the view's getDrawingRect, but I'm not sure it is a proper way, because it seems that the canvas parameter of onDraw should be all-sufficient for drawing sizing.
I had the same issue, here is how I got this fixed, hope it helps you
protected void onDraw(Canvas c) {
super.onDraw(c);
int w = getWidth(), h = getHeight();
// resize
Matrix resize = new Matrix();
resize.postScale((float)Math.min(w, h) / (float)mMarker.getWidth(), (float)Math.min(w, h) / (float)mMarker.getHeight());
imageScaled = Bitmap.createBitmap(mMarker, 0, 0, mMarker.getWidth(), mMarker.getHeight(), resize, false);
c.drawBitmap(imageScaled, 0,0, paint);
}
Where mMarker is defined in the custom ImageView constructor.
...
private Bitmap mMarker, imageScaled;
Paint paint = new Paint();
//Java constructor
public AvatarImageView(Context context) {
super(context);
init();
}
//XML constructor
public AvatarImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// load the image only once
mMarker = BitmapFactory.decodeResource(getResources(), R.drawable.silhouette_48);
mMarker.setHasAlpha(true);paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(4);
//invalidate(); // don't know if I need this
}

How to rotate a drawable with anti-aliasing enabled

I need to rotate an ImageView by a few degrees. I'm doing this by subclassing ImageView and overloading onDraw()
#Override
protected void onDraw(Canvas canvas) {
canvas.save();
canvas.scale(0.92f,0.92f);
canvas.translate(14, 0);
canvas.rotate(1,0,0);
super.onDraw(canvas);
canvas.restore();
}
The problem is that the image that results shows a bunch of jaggies.
http://img.skitch.com/20100608-gmdy4sexsm1c71di9rgiktdjhu.png
How can I antialias an ImageView that I need to rotate in order to eliminate jaggies? Is there a better way to do this?
If you know that your Drawable is a BitmapDrawable, you can use anti-aliasing in the bitmap's Paint to do something like the following:
/**
* Not as full featured as ImageView.onDraw(). Does not handle
* drawables other than BitmapDrawable, crop to padding, or other adjustments.
*/
#Override
protected void onDraw(Canvas canvas) {
final Drawable d = getDrawable();
if( d!=null && d instanceof BitmapDrawable && ((BitmapDrawable)d).getBitmap()!=null ) {
final Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
canvas.save();
// do my rotation and other adjustments
canvas.scale(0.92f,0.92f);
canvas.rotate(1,0,0);
if( paddingLeft!=0 )
canvas.translate(paddingLeft,0);
if( paddingTop!=0 )
canvas.translate(0,paddingTop);
canvas.drawBitmap( ((BitmapDrawable)d).getBitmap(),0,0,p );
canvas.restore();
}
}
Set antialias and filterBitmap to the paint that draw's the bitmap.
I had a similar problem and this worked for me:
Paint bitmapPaint = new Paint();
bitmapPaint.setAntiAlias(true);
bitmapPaint.setFilterBitmap(true);
I did the following to get it to work:
In AndroidManifest.xml I enabled hardware-acceleration <application android:hardwareAccelerated="true">.
Instead of using a custom draw-method, I changed the layer-type of the parent-view to hardware-accelerated with anti-aliasing enabled and added my subviews as follows:
Paint layerPaint = new Paint();
layerPaint.setAntiAlias(true);
layerPaint.setFilterBitmap(true);
layerPaint.setDither(true);
RelativeLayout parentLayout = (RelativeLayout) LayoutInflater.from(context).inflate(R.layout.myLayout, null);
parentLayout.setLayerType(View.LAYER_TYPE_HARDWARE, layerPaint);
parentLayout.addView(myChildView);
I have to add that clipping cannot be disabled when using this approach.
This rotation solves just one part of problem - jagged edges, but the image instead became wierd.
ifound only one solution yet:
in ondraw or dispatch draw method
Bitmap bmp = ((BitmapDrawable)image.getDrawable()).getBitmap();
double scale = (0.0+bmp.getWidth()+40.0)/getWidth();
if (scale > 1){
bmp = Bitmap.createScaledBitmap(bmp, getWidth()-40, (int) (bmp.getHeight()/scale), true);
}
canvas.drawColor(Color.TRANSPARENT);
canvas.save();
canvas.translate(20, yShift);
int left = borderSize;
int top = borderSize;
int right = bmp.getWidth() - borderSize;
int bottom = bmp.getHeight() - borderSize;
if(showText){
mPaint.setColor(Color.WHITE);
canvas.rotate(getAngel());
canvas.drawRect(left, top, right, bottom, mPaint);
canvas.translate(0,0);
textFrame.draw(canvas);
}else{
// rotaed bitmap
mMatrix.setRotate(getAngel());
// draw bitmap after creation of new rotated bitmap from rotated matrix
canvas.drawBitmap(Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mMatrix, true)
, 0, 0, mPaint);
}
canvas.restore();
#Primoz990's solution worked for me :) I also enabled Dithering, so my final code which removes the jagged edges on rotation is this:
Paint bitmapPaint = new Paint();
bitmapPaint.setAntiAlias(true);
bitmapPaint.setFilterBitmap(true);
bitmapPaint.setDither(true);

Categories

Resources